Skip to content

Case study: ATM workflow

Difficulty: Advanced

Key concepts

  • session state machine
  • std::variant states
  • hold and commit
  • write-ahead journal
  • recovery after a crash
  • idempotent bank requests
  • transaction id
  • sealed PIN block
  • daily limit
  • deposit escrow
  • How to model a customer’s session (card in, PIN, choices, card out) as a state machine whose states are types, so that a bank session cannot exist in a state where it makes no sense.
  • Why an ATM asks the bank to hold money before it gives out cash, and commits only after, and what goes wrong in the other order.
  • How a journal written before each step lets a machine that lost power in the middle of a withdrawal work out what may have happened, and finish the job without charging twice or paying twice.
  • Which failures software can finish on its own, and which only a person counting the cassette can, and how the design keeps the two apart.
  • How one id per withdrawal makes every request to the bank safe to repeat, and why that id must come from the journal, not from a counter in memory.
  • Where the PIN may and may not go: a trust boundary that the ATM’s own code stays outside of.
  • How a change (a daily limit across every ATM, and deposits) lands: one rule in the bank, and a deposit that is a withdrawal in reverse.

This page follows the order in How to approach a case study. It assumes State machines and invalid-state prevention, Security-sensitive boundaries, and Transaction and persistence boundaries. Those pages build each idea on its own; this one needs all three at once, in a program where money and paper move in different places and can disagree.

“We are replacing the software in our ATMs. The old code was written for a machine that never loses power and a bank that always answers. Last year a cassette jammed and we charged forty customers for cash they never got. Another time the network dropped after the cash came out and nobody was charged. Can you design the part that runs a customer’s session and the withdrawal?”

Two complaints, and they are mirror images. One machine took money for cash it did not give; another gave cash it never took money for. Both happened because the software did one thing, then another, and assumed that nothing could stop it between the two.

Each question is here because its answer changes the design.

Question Answer (from the team) What it changes
What can the bank do for us? Check a PIN and open a session, give a balance, and hold money, then take it or give it back. Each held amount has an id that we choose. A Bank interface with verify, available, hold, commit, and release. The ATM chooses the id.
Does the bank always answer? No. Requests time out, and sometimes the bank did the work and the answer was lost. “No answer” is an ordinary result, not an exception, and every request must be safe to send again.
Who decides whether a PIN is right? The bank. The PIN pad encrypts the PIN, and our software must never see it. The ATM passes on a sealed PinBlock it cannot read. It never compares PINs.
After how many wrong PINs do we keep the card? Three, counted by the bank, across all our machines. The bank counts. The ATM only does what the bank says.
How does the dispenser fail? Mostly it fails to pick the first note and gives nothing. Sometimes it jams part way, and then nobody knows how many notes came out. Three outcomes: all, nothing, or unknown. Unknown means a person counts.
What happens after a jam today? An engineer opens the safe and counts the cassette against the machine’s records. A withdrawal can wait for an operator, and the machine is out of service until then.
Can the machine lose power in the middle of a withdrawal? Yes, a few times a year per machine. It reboots and must carry on. A journal on disk, written before each step, read on start-up.
What does a customer take first, the card or the cash? The card. People forget a card once they have the money. The card comes out, then the cash.
Which notes, and how much at a time? One cassette of 20s in this model. At most 400 per withdrawal at this machine. One denomination; a per-machine limit in the config.
How long does a session wait for the customer? 30 seconds of no input, then the card comes back. A timeout, checked by a tick from a timer.
Do we show the card number anywhere? Only the last four digits, on screen and in logs. The journal stores a masked card number.
One customer at a time? Yes. One card reader, one thread for events. Step 1 is single-threaded and says so.

Three answers decide the shape. “Hold, then take it or give it back” puts the irreversible step, notes leaving the machine, between two bank requests that can be redone. “It reboots and must carry on” makes a journal the first thing written and the first thing read. “Nobody knows how many notes came out” means some withdrawals cannot be finished by software at all, and the design must say which.

Confirmed:

  • A session: card in, PIN checked by the bank, balance and withdrawal, cancel, timeout, card out.
  • Cards kept when the bank says so.
  • Withdrawals in whole notes, up to a limit per withdrawal and the cash in the cassette.
  • A bank that may not answer, or may answer late, at every step.
  • A dispenser that may give everything, nothing, or an unknown amount.
  • Recovery after a power cut, from a journal.
  • An operator who counts after a jam and tells the machine what they found.

Assumed (to confirm with the team; see Assumptions):

  • Every machine has a unique id, such as atm-7, and the bank keys held amounts by an id that starts with it.
  • The bank keeps a hold until it is committed or released, however long that takes. (A real bank also lets holds expire, and settles them with the machine’s records later.)
  • The journal is written to storage that survives a power cut, and an append returns only once it is safe there. The example keeps it in memory, so that a test can “restart” the machine on the same journal.

Out of scope: the bank’s side (the example has a fake bank), encryption of the PIN (the example has a toy stand-in, marked as such), receipts, card-scheme messages, cassettes of several denominations, and the screen and keypad drivers. Daily limits and deposits arrive as a change, below.

Functional requirements.

  • FR-1 Session. A card and a PIN accepted by the bank open a session. A wrong PIN may be tried again while the bank allows it; when the bank says to keep the card, the machine keeps it. An unknown card is returned. If the bank does not answer, the card is returned.
  • FR-2 Balance. In a session, the customer can see how much money is available: the balance less any money on hold.
  • FR-3 Withdrawal. In a session, the customer can take out an amount that is a whole number of notes, no more than the machine’s limit per withdrawal, and no more than the cash in the cassette. The card comes out before the cash.
  • FR-4 No money without cash, no cash without money. Whatever fails (the bank, the dispenser, the power), the customer is charged exactly for the cash that left the machine.
  • FR-5 Recovery. After a restart, the machine finishes every withdrawal that software can finish. One that only a count of the cassette can settle waits for an operator, and the machine is out of service until then.
  • FR-6 Sessions end. Cancel ends a session and returns the card, and so do 30 seconds with no input. Every way out that the ATM controls ends the session at the bank. A power cut cannot, so the bank must expire a session it has not heard from.
  • FR-7 Out of service. With no cash left, or a withdrawal waiting for an operator, the machine returns any card at once.

Non-functional requirements.

  • NFR-1 The PIN stays sealed. The ATM’s code never holds a PIN it can read, and keeps no whole card number.
  • NFR-2 Every bank request is safe to repeat. Each withdrawal has an id, and a request sent twice under it has the effect of one.
  • NFR-3 Testable without hardware. The bank, the dispenser, and the clock are interfaces. Every failure in this list can be produced on demand by a fake.
  • NFR-4 Not thread-safe, on purpose. One thread delivers every event, and the documentation says so.
  • NFR-5 Exact money. Amounts are integer cents, never floating point.

FR-4 is both of the team’s complaints in one line. Most of this design is about keeping it when a step in the middle of a withdrawal does not happen, happens without the machine knowing, or happens and then the machine loses power.

The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.

UC-1 Start and end a session.

  • AC-1.1 A card and the right PIN open a session at the bank.
  • AC-1.2 Wrong PINs are counted by the bank, across ATMs: two wrong at one machine and one at another keep the card. The right PIN resets the count.
  • AC-1.3 A blocked card is kept; an unknown card is returned.
  • AC-1.4 If the bank does not answer a PIN, the card is returned.
  • AC-1.5 Cancel returns the card and ends the bank session, before or after the PIN.
  • AC-1.6 A session with no input ends after the timeout, and not one second before.
  • AC-1.7 An event in the wrong state (a withdrawal with no card, a second card) changes nothing and writes nothing.
  • AC-1.8 No PIN and no whole card number is kept: the sealed PIN does not contain the digits, and the journal shows only the last four.

UC-2 Check the balance.

  • AC-2.1 The balance is the money available less holds, including holds made at another ATM.
  • AC-2.2 A balance the bank does not answer can be asked for again; the session stays open.

UC-3 Withdraw cash.

  • AC-3.1 A withdrawal returns the card, gives the cash, and commits the hold.
  • AC-3.2 An amount that is not whole notes, above the limit, or more than the cassette holds is refused before the bank hears of it.
  • AC-3.3 Not enough money holds nothing, and the session stays open for another amount.
  • AC-3.4 A hold the bank does not answer is released, because it may have arrived.
  • AC-3.5 A release the bank does not answer is finished later by settle.
  • AC-3.6 A dispenser that gives nothing releases the hold.
  • AC-3.7 A lost reply to a commit is sent again later, and the customer is charged once.
  • AC-3.8 A jam keeps the hold and takes the ATM out of service.
  • AC-3.9 A dispenser that throws is treated as a jam.
  • AC-3.10 The last notes take the ATM out of service.

UC-4 Recover.

  • AC-4.1 After a crash at any stage that software can finish, settle finishes it: commits if the cash left, releases if it did not or may never have been held.
  • AC-4.2 A crash while notes were being counted out waits for an operator, and the ATM starts out of service.
  • AC-4.3 Ids never repeat after a restart.
  • AC-4.4 resolve accepts only a withdrawal that waits for an operator.
  • AC-4.5 The journal refuses a second start for a known id, a first entry that is not a start, and anything after a final stage.
  • AC-4.6 The fake bank keeps the contract: commit and release are safe to repeat, a late hold for a released id is refused.

UC-5 Set up.

  • AC-5.1 A config with no id, a note that is not positive, a limit below one note, or a timeout that is not positive is rejected.

Each invariant names the code that keeps it. See Invariants.

  • INV-1 Write ahead. Before every request to the bank about a withdrawal, and before notes move, the journal holds an entry naming that withdrawal at the stage about to begin. Kept by Atm::withdraw, which calls record before hold and before dispense.
  • INV-2 A hold is committed only after its cash left. commit is called only for a withdrawal whose last stage is dispensed. Kept by Atm::finish, the only code that calls commit.
  • INV-3 Nothing is left open by accident. Every withdrawal that is not final is either one settle can finish (holding, dispensed, not dispensed), or one waiting for an operator (dispensing, jammed), and then the machine is out of service. Kept by needs_operator, resting_state, and tick, which calls settle.
  • INV-4 An id is used once. No two withdrawals share an id, even across restarts. Kept by next_id, which numbers from the journal, and by Journal::append, which refuses a second start for a known id.
  • INV-5 A bank session exists only in Ready. Kept by the state types: only Ready has a session member, and end_session ends it on every way out the ATM controls. After a power cut, the bank’s expiry ends it instead.
  • INV-6 The journal only moves forward. A new id starts at holding, and nothing follows a final stage. Kept by Journal::append.
  • INV-7 The money adds up. Over any run, the account falls by exactly the cash that left the machine, and once every withdrawal is final, nothing is held. A consequence of INV-1 to INV-4, checked by the random test.

The random test makes 4,000 random steps with every failure on, and checks INV-7 at the end, and after every step that the bank never holds more than the open withdrawals.

The nouns from the answers: card, PIN, session, bank, balance, hold, withdrawal, id, note, cassette, dispenser, jam, power cut, journal, operator, timeout, machine. Filtered:

  • Card is a card number, a std::string, kept whole only in memory for the session and masked everywhere else.
  • PIN is a PinBlock: sealed bytes the ATM forwards and cannot read.
  • Session is a state of the machine (AwaitingPin, Ready), and a session id that the bank gave.
  • Bank, balance, and hold become the Bank interface, its BalanceReply, and the hold, commit, and release requests.
  • Withdrawal and id become a TxnId and the journal’s entries for it. There is no Withdrawal object: a withdrawal is its entries, because they are what survives a power cut.
  • Note, cassette, dispenser, and jam become the CashDispenser interface and its DispenseStatus.
  • Journal is a Journal of Entry values, each with a Stage.
  • Operator is a caller of Atm::resolve. Timeout is a tick and a Clock. Power cut is destroying the Atm and building another on the same journal.
  • Machine is the Atm, with an AtmConfig.
Classes in step 1. Filled diamond: owns. Plain arrow: uses, not owned
Text description of the diagram

Atm holds its config and its state, and pointers to a Bank, a CashDispenser, a Journal, and a Clock, none of which it owns. It offers insert_card, enter_pin, check_balance, withdraw, cancel, tick, settle, and resolve. Bank is an interface with verify, available, hold, commit, release, and end; FakeBank implements it. CashDispenser is an interface with notes_left and dispense; FakeDispenser implements it. Clock is an interface with now; ManualClock implements it. Journal owns a vector of Entry values (id, masked card, amount, stage, time) and a map from id to the position of its latest entry, and offers append, open, and started. Atm forwards a PinBlock, which holds sealed bytes, to the bank without reading it.

Diagram source (Mermaid)
classDiagram
class Atm {
  -AtmConfig config_
  -Bank* bank_
  -CashDispenser* dispenser_
  -Journal* journal_
  -const Clock* clock_
  -State state_
  +insert_card(card) Response
  +enter_pin(const PinBlock&) Response
  +check_balance() Response
  +withdraw(Money) Response
  +cancel() Response
  +tick() Response
  +settle() size_t
  +resolve(id, bool cash_left_machine)
}
class Bank {
  <<interface>>
  +verify(card, const PinBlock&) PinReply*
  +available(session) BalanceReply*
  +hold(session, id, Money) BankStatus*
  +commit(id) BankStatus*
  +release(id) BankStatus*
  +end(session)*
}
class CashDispenser {
  <<interface>>
  +notes_left() int*
  +dispense(int notes) DispenseStatus*
}
class Clock {
  <<interface>>
  +now() TimePoint*
}
class Journal {
  -vector~Entry~ entries_
  -map~TxnId, size_t~ last_
  +append(Entry)
  +open() vector~Entry~
  +started() size_t
}
class Entry {
  +TxnId id
  +string card
  +Money amount
  +Stage stage
  +TimePoint at
}
class PinBlock {
  -string sealed_
  +sealed() const string&
}
Bank <|.. FakeBank
CashDispenser <|.. FakeDispenser
Clock <|.. ManualClock
Atm --> Bank : uses
Atm --> CashDispenser : uses
Atm --> Journal : appends, reads
Atm --> Clock : reads
Journal *-- Entry : entries_
Atm ..> PinBlock : forwards

Ownership is simple and worth saying out loud. The Atm owns its config and its state, and nothing else. The bank, the dispenser, the journal, and the clock are owned by whoever builds the machine, the composition root, and must outlive it. That is not only tidiness: the journal must outlive an Atm, because a restart is a new Atm reading the same journal. The tests and the demo restart a machine by destroying it and building another on the same objects.

The design below is step 1 of the example, the complete answer to FR-1 … FR-7. Daily limits and deposits are added in When the requirements change.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

money.hpp
// An amount in cents. Never a double: a bank adds and subtracts exactly,
// and 0.1 + 0.2 is not 0.3 in binary floating point.
// std::int64_t is a whole number of exactly 64 bits, so even very large
// balances fit. Money{} is zero, and Money{13000} is 130.00.
struct Money {
std::int64_t cents = 0;
// `<=> ... = default` asks the compiler to write every comparison
// (==, !=, <, <=, >, >=) by comparing `cents`, so amounts can be
// compared like numbers. `friend` inside the struct makes these free
// functions that the compiler finds whenever a Money is involved.
friend constexpr auto operator<=>(const Money&, const Money&) = default;
// Adding or subtracting two amounts gives a new amount. The arguments
// are taken by value: a Money is one number, as cheap to copy as an
// int. `{a.cents + b.cents}` builds the Money to return.
friend constexpr Money operator+(Money a, Money b) { return {a.cents + b.cents}; }
friend constexpr Money operator-(Money a, Money b) { return {a.cents - b.cents}; }
};
// dollars(20) is 2000 cents: a readable way to write whole amounts.
[[nodiscard]] constexpr Money dollars(std::int64_t whole) { return {whole * 100}; }
// "120.00", or "-5.50". Works on the size of the amount (its magnitude)
// and puts the minus sign back at the end, because % and / on a negative
// number give negative parts in C++ (-550 % 100 is -50).
[[nodiscard]] inline std::string to_string(Money money) {
const std::int64_t magnitude = money.cents < 0 ? -money.cents : money.cents;
// The cents part, 0 to 99. A single digit gets a leading zero, so
// 5 cents prints as "05" and 12005 cents as "120.05", not "120.5".
std::string cents = std::to_string(magnitude % 100);
if (cents.size() < 2) cents.insert(0, "0");
// Whole units are magnitude / 100: integer division drops the cents.
return (money.cents < 0 ? "-" : "") + std::to_string(magnitude / 100) + "." + cents;
}

Money is a count of cents in a std::int64_t, with only the operations a withdrawal needs: add, subtract, compare. It is a value object, and a small instance of Strong types: a function that takes Money cannot be given a count of notes by mistake.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

clock.hpp
// Where the ATM gets the time: for session timeouts and for the times in
// its journal. The tests and the demo pass ManualClock and move time by
// hand, so a timeout is checked to the second and nothing sleeps.
// TimePoint is a shorter name for "a moment on the wall clock". Taking
// one from another gives a duration, which is how a timeout is measured.
using TimePoint = std::chrono::system_clock::time_point;
// An interface: its one real function, now(), is `= 0` (pure virtual), so
// a bare Clock cannot be made; a class that derives from it supplies now().
// The Atm holds a `const Clock*` and never knows which clock it has.
class Clock {
public:
// Virtual, so destroying a derived clock through a Clock is safe.
virtual ~Clock() = default;
[[nodiscard]] virtual TimePoint now() const = 0;
protected:
// Protected: only derived classes can build or copy a Clock, so code
// cannot copy a bare Clock and lose the derived part (slicing).
Clock() = default;
Clock(const Clock&) = default;
Clock& operator=(const Clock&) = default;
};
// The real time, for a real machine. `final` says nothing derives from it.
class SystemClock final : public Clock {
public:
[[nodiscard]] TimePoint now() const override { return std::chrono::system_clock::now(); }
};
// A clock that stands still until it is told to move: the time is
// whatever it was built with, plus every advance() since.
class ManualClock final : public Clock {
public:
// `explicit` stops a TimePoint from turning into a ManualClock by
// accident, for example when passed to a function.
explicit ManualClock(TimePoint start) : now_(start) {}
[[nodiscard]] TimePoint now() const override { return now_; }
// Throws std::invalid_argument for a negative step.
void advance(std::chrono::seconds step) {
if (step.count() < 0) throw std::invalid_argument("time only moves forward here");
now_ += step;
}
private:
TimePoint now_;
};

The timeout needs the time, and tests need to move it. A Clock interface with a ManualClock lets ac_1_6 check the 30-second timeout to the second without sleeping.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

pin.hpp
// What the PIN pad hands to the ATM: the PIN, sealed so that only the
// bank can read it. A real ATM has an encrypting PIN pad, a sealed piece
// of hardware that encrypts the PIN with a key the ATM's software never
// holds. So the ATM's code can forward a PinBlock, but has no way to read
// the PIN in it, and nothing here compares, prints, or stores one.
class PinBlock {
public:
// Takes the sealed text by value and moves it into the member, so the
// caller's string is not copied a second time. explicit: a plain
// string never turns into a PinBlock without the caller saying so.
explicit PinBlock(std::string sealed) : sealed_(std::move(sealed)) {}
// The sealed bytes, for the message to the bank. Not the PIN. Returns
// a const reference: a look at the member, not a copy, valid while
// this PinBlock lives. noexcept: it cannot throw.
[[nodiscard]] const std::string& sealed() const noexcept { return sealed_; }
private:
std::string sealed_;
};

PinBlock has no way to get the PIN out. It has no comparison, no stream output, and its only accessor returns the sealed bytes, which are for the message to the bank. The ATM’s code can forward it and nothing else. That is the shape of the real thing, where an encrypting PIN pad seals the PIN in hardware with a key that the ATM’s software never holds; see Trust boundaries.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

pin.hpp
// A stand-in for the PIN pad and for the bank's side of the key, so the
// demo and the tests can run. The "sealing" is a toy that only hides the
// digits from a casual reader. It is not encryption: do not copy it into
// anything that handles real PINs.
namespace toy {
// The PIN pad's side: turns the typed digits into a PinBlock, using key.
// std::string_view lets a caller pass "4321" without building a string.
// Throws std::invalid_argument unless digits is 4 to 6 digits, as the
// pad's keys allow.
[[nodiscard]] PinBlock seal(std::string_view digits, unsigned key);
// The bank's side: gets the digits back, given the same key. Only the
// fake bank calls it; the Atm never does.
[[nodiscard]] std::string unseal(const PinBlock& pin, unsigned key);
} // namespace toy

The demo and the tests need something that makes a PinBlock and something that reads it on the bank’s side. This toy does both with a key, and says plainly that it is not encryption. Keeping it in its own namespace, toy, makes every use of it easy to find.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

bank.hpp
// The ATM's id for one movement of money: the machine's id and a
// sequence number, such as "atm-7-000042". The bank keys holds by it,
// which makes commit and release safe to repeat after a lost reply or a
// restart.
using TxnId = std::string;
// What the bank says about a card and a PIN.
enum class PinResult {
accepted,
wrong_pin, // tries_left says how many are left
card_retained, // too many wrong PINs, or a blocked card: keep the card
card_unknown, // not a card this bank knows
unavailable, // no answer
};
// The whole answer to verify. Each member starts with a safe default, so
// `return {};` means "no answer" and `{PinResult::card_unknown}` fills in
// only the first member. Only some members mean something for each result.
struct PinReply {
PinResult result = PinResult::unavailable;
std::string session{}; // when accepted: names this card's session at the bank
int tries_left = 0; // when wrong_pin
};
// The answer to every request about money. unavailable is the one to
// think hardest about: the request may have been done and only the reply
// lost, so the ATM must be able to send it again safely.
enum class BankStatus {
ok,
insufficient_funds, // a hold for more than is available
unknown, // no such session, or no such transaction
conflict, // the transaction already ended the other way
unavailable, // no answer: the request may or may not have been applied
};
// The answer to available: a status, and the amount when it is ok.
struct BalanceReply {
BankStatus status = BankStatus::unavailable;
Money available{}; // the balance less the money on hold, when ok
};
// The ATM's view of its bank. Network failures are answers
// (unavailable), not exceptions; an implementation throws only for a
// programming error, such as a hold for zero. An interface (every function
// is `= 0`): FakeBank implements it for the demo and the tests, and a real
// network client would implement it in production.
class Bank {
public:
virtual ~Bank() = default;
// The bank counts wrong PINs per card, across every ATM, and says
// when the ATM must keep the card.
[[nodiscard]] virtual PinReply verify(const std::string& card, const PinBlock& pin) = 0;
// The money the customer can use now. Needs the session that an
// accepted verify returned.
[[nodiscard]] virtual BalanceReply available(const std::string& session) = 0;
// Reserves amount under id. A repeat with the same id and amount is
// ok and reserves nothing more. A hold for an id already released is
// a conflict, so a hold that arrives late cannot reserve money again.
[[nodiscard]] virtual BankStatus hold(const std::string& session, const TxnId& id, Money amount) = 0;
// Takes the held money for good. Safe to repeat.
[[nodiscard]] virtual BankStatus commit(const TxnId& id) = 0;
// Gives the held money back. Safe to repeat, and ok for an id the
// bank has never seen: the hold that the ATM sent may not have
// arrived. A conflict after a commit.
[[nodiscard]] virtual BankStatus release(const TxnId& id) = 0;
// Closes a session. noexcept and no result: ending a session must
// always "work" from the ATM's side, even if the message is lost.
virtual void end(const std::string& session) noexcept = 0;
protected:
// As for Clock: only derived classes may build or copy a Bank.
Bank() = default;
Bank(const Bank&) = default;
Bank& operator=(const Bank&) = default;
};

Every request about money is keyed by a TxnId that the ATM chooses, and the contract says what a repeat does:

  • hold with the same id and amount is ok and reserves nothing more.
  • commit and release are safe to repeat.
  • release of an id the bank has never seen is ok. The ATM may have sent a hold that never arrived, and it has no way to tell that from a hold whose answer was lost, so it must be able to release either.
  • hold for an id already released is a conflict. Without that rule, a hold delayed in the network could arrive after its release and reserve the money again, for a withdrawal the ATM has given up on.

That is idempotency keyed by the ATM’s id, as in Idempotency, retries, and duplicate handling: the ATM may send any request again, as often as it likes, and the effect is that of one. And “no answer” is a BankStatus, not an exception, because it is an ordinary outcome that every caller must handle, not a bug.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

fake_bank.hpp
// A stand-in for the bank's side, for the demo and the tests. It keeps
// accounts, counts wrong PINs, and keeps holds by transaction id, as the
// Bank contract says. It can be told to fail its next call of one kind,
// either before doing anything or after (the reply is lost).
// Names one kind of request, so a test can say which one to fail.
enum class BankCall { verify, available, hold, commit, release };
class FakeBank final : public Bank {
public:
// The third wrong PIN with no right one in between keeps the card.
static constexpr int max_tries = 3;
// pin_key must be the key the PIN pad (toy::seal) used, or no PIN matches.
explicit FakeBank(unsigned pin_key) : pin_key_(pin_key) {}
// Test set-up. open_account throws std::invalid_argument for a card
// that already has an account. block marks a card as blocked, so the
// next verify keeps it; .at() throws std::out_of_range for an unknown card.
void open_account(const std::string& card, std::string pin, Money balance);
void block(const std::string& card) { accounts_.at(card).blocked = true; }
// The next call of this kind returns unavailable. With applied, it
// does its work first, so only the reply is lost.
// `failures_[call] = applied` adds the switch, or replaces one already
// set for that kind. The next call of that kind removes it, so each
// switch fails exactly one call.
void fail_next(BankCall call, bool applied = false) { failures_[call] = applied; }
// For checks in tests: the account's balance, the total still on hold
// for the card, and how many sessions are open.
[[nodiscard]] Money balance(const std::string& card) const { return accounts_.at(card).balance; }
[[nodiscard]] Money held(const std::string& card) const;
[[nodiscard]] std::size_t open_sessions() const noexcept { return sessions_.size(); }
[[nodiscard]] PinReply verify(const std::string& card, const PinBlock& pin) override;
[[nodiscard]] BalanceReply available(const std::string& session) override;
[[nodiscard]] BankStatus hold(const std::string& session, const TxnId& id, Money amount) override;
[[nodiscard]] BankStatus commit(const TxnId& id) override;
[[nodiscard]] BankStatus release(const TxnId& id) override;
// Erasing a session that is not there does nothing, so this is safe to
// repeat, and it cannot throw.
void end(const std::string& session) noexcept override { sessions_.erase(session); }
private:
// One customer's account: their PIN (kept here, at the "bank", never in
// the Atm), money, and the count of wrong PINs in a row.
struct Account {
std::string pin;
Money balance;
int wrong = 0;
bool blocked = false;
};
// A hold starts held and ends committed (the money is taken) or
// released (it is given back), and never moves on from either. A
// release for an id never seen makes one that is released from the start.
enum class HoldState { held, committed, released };
struct Hold {
std::string card; // empty for a release of an id never held
Money amount;
HoldState state = HoldState::held;
};
// True if this call must fail; then applied says whether to do it first.
bool failing(BankCall call, bool& applied);
// Each std::map is a sorted table from a key to a value. Keeping holds_
// by TxnId is what makes a repeat recognisable: the same id finds the
// same hold, so it is not reserved twice.
unsigned pin_key_;
std::map<std::string, Account> accounts_; // card -> account
std::map<std::string, std::string> sessions_; // session -> card
std::map<TxnId, Hold> holds_;
std::map<BankCall, bool> failures_; // the fail_next switches still waiting
int next_session_ = 1; // sessions are named "s-1", "s-2", ...
};

The fake bank is a test double that keeps the contract (AC-4.6 tests that it does) and can fail its next call of each kind in two ways: before doing anything, or after, so that only the reply is lost. The second way is the one that matters most, and the one a simpler fake would leave out.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

dispenser.hpp
// How a dispense ended, as the hardware reports it.
enum class DispenseStatus {
dispensed, // every note was counted out and presented to the customer
failed, // nothing left the cassette: a pick failure before the first note
jammed, // stopped part way: how many notes left the machine is not known
};
// The cash dispenser's driver, as the ATM sees it. One denomination. An
// interface, like Clock and Bank: FakeDispenser implements it here, and a
// real driver would on a real machine.
class CashDispenser {
public:
virtual ~CashDispenser() = default;
// How many notes are in the cassette, so the ATM can refuse an amount
// it cannot give before asking the bank for anything.
[[nodiscard]] virtual int notes_left() const noexcept = 0;
// Counts out notes and presents them. Throws only for a programming
// error, such as more notes than are left.
[[nodiscard]] virtual DispenseStatus dispense(int notes) = 0;
protected:
CashDispenser() = default;
CashDispenser(const CashDispenser&) = default;
CashDispenser& operator=(const CashDispenser&) = default;
};

Three outcomes, and the third is the reason for most of this design: jammed means the machine does not know how many notes left. The driver could guess, but a guess about money is worse than “unknown”, because “unknown” tells the software to stop and ask a person.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

dispenser.hpp
// A stand-in for the hardware. It can be told how its next dispense ends.
// It never fails on its own: only fail_next makes a dispense go wrong.
class FakeDispenser final : public CashDispenser {
public:
// A cassette loaded with `notes` notes. Throws std::invalid_argument
// for a negative count.
explicit FakeDispenser(int notes) : left_(notes) {
if (notes < 0) throw std::invalid_argument("a cassette cannot hold fewer than no notes");
}
// How the next dispense ends. For a jam, notes_out says how many
// notes reached the customer before it stopped; the ATM cannot see it.
// Only the next dispense: dispense() clears the setting once used.
void fail_next(DispenseStatus how, int notes_out = 0) {
next_ = how;
jam_out_ = notes_out;
}
// How many notes have left the machine in total, for the checks.
[[nodiscard]] int presented() const noexcept { return presented_; }
[[nodiscard]] int notes_left() const noexcept override { return left_; }
// Asking for fewer than one note, or more than are left, is a
// programming error, so it throws (the Atm checks notes_left first).
[[nodiscard]] DispenseStatus dispense(int notes) override {
if (notes < 1 || notes > left_) throw std::invalid_argument("cannot dispense that many notes");
// The outcome a test set with fail_next, or "dispensed" if none was
// set: value_or gives the optional's value, or the fallback when it
// is empty. reset() empties it, so the failure happens only once.
const DispenseStatus how = next_.value_or(DispenseStatus::dispensed);
next_.reset();
// How many notes actually left: all of them, the number the test
// chose for a jam, or none for a failure. Two `?:` in a row read
// as "if dispensed then notes, else if jammed then jam_out_, else 0".
const int out = how == DispenseStatus::dispensed ? notes : how == DispenseStatus::jammed ? jam_out_ : 0;
if (out > notes) throw std::invalid_argument("a jam cannot let out more notes than were asked for");
// Only `how` goes back to the ATM; `out` stays inside the fake,
// where a test, playing the operator who counts, can read it.
left_ -= out;
presented_ += out;
return how;
}
private:
int left_; // notes still in the cassette
int presented_ = 0; // notes given out, ever
std::optional<DispenseStatus> next_; // empty: the next dispense works
int jam_out_ = 0; // notes out in the next jam
};

FakeDispenser::fail_next(DispenseStatus::jammed, n) jams with n notes out. The ATM cannot see n; only the test, playing the operator who counts, uses it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

journal.hpp
// Where a withdrawal has got to. The ATM writes the next stage BEFORE
// each step whose effect it cannot see (a request to the bank, notes
// leaving the cassette), and the result after it. After a crash, the last
// stage of each withdrawal says what may have happened, and so what is
// still to do.
enum class Stage {
holding, // a hold was asked for; the bank may or may not have it
dispensing, // notes were being counted out; how many left is not known
dispensed, // the customer has the cash; the hold is still to commit
not_dispensed, // no cash left the machine; the hold is still to release
jammed, // stopped part way; an operator must count the cassette
committed, // final: the customer paid
released, // final: the customer paid nothing
};
// The name of a stage, for the demo's output and for error messages. A
// std::string_view of a string literal is safe to return: the literal
// lasts for the whole program. The switch names every stage and has no
// default, so a compiler warns if a new stage is added and not named
// here; the `return "?"` after it is never reached for a real Stage.
[[nodiscard]] constexpr std::string_view to_string(Stage stage) noexcept {
switch (stage) {
case Stage::holding: return "holding";
case Stage::dispensing: return "dispensing";
case Stage::dispensed: return "dispensed";
case Stage::not_dispensed: return "not dispensed";
case Stage::jammed: return "jammed";
case Stage::committed: return "committed";
case Stage::released: return "released";
}
return "?";
}
// Final stages end a withdrawal: nothing may be appended after them.
[[nodiscard]] constexpr bool is_final(Stage stage) noexcept {
return stage == Stage::committed || stage == Stage::released;
}
// Stages that software cannot finish: someone must count the cash. A
// withdrawal left at one of these keeps the machine out of service.
[[nodiscard]] constexpr bool needs_operator(Stage stage) noexcept {
return stage == Stage::dispensing || stage == Stage::jammed;
}
// One line of the journal: which withdrawal, for how much, the stage it
// reached, and when. A withdrawal is several entries with the same id,
// one per stage; the latest one is where it has got to.
struct Entry {
TxnId id;
std::string card; // masked: "****1234"
Money amount{};
Stage stage = Stage::holding;
TimePoint at{};
};
// Append-only. Here it lives in memory, owned by main, so that a test can
// destroy an Atm and build a new one on the same journal, as a restart
// would. A real journal is a file that is flushed to disk on every append.
// Entries are only ever added at the end, never changed or removed, so
// the full history of every withdrawal stays readable.
class Journal {
public:
// Throws std::invalid_argument for an entry that does not follow the
// last one of its withdrawal: a new id must start at holding, and
// nothing follows a final stage.
// Takes the entry by value, so it can be moved into the journal. If it
// throws, the journal is left as it was.
void append(Entry entry);
// Every entry, oldest first. A const reference: callers can read the
// journal's own vector but not change it, and no copy is made.
[[nodiscard]] const std::vector<Entry>& entries() const noexcept { return entries_; }
// The last entry of every withdrawal that is not final, in id order:
// for one machine's zero-padded ids, the order they started.
// Returns copies, in a new vector, so a caller may append to the
// journal while looping over the result (as settle does).
[[nodiscard]] std::vector<Entry> open() const;
// How many withdrawals were ever started: the next sequence number
// follows it, so an id is never used twice, even after a restart.
[[nodiscard]] std::size_t started() const noexcept { return last_.size(); }
private:
std::vector<Entry> entries_;
// id -> position of its latest entry, so that append does not scan
// entries_. A journal kept in a file rebuilds it when read at start-up.
// It holds positions, not pointers: push_back may move the vector's
// entries to new memory, which would leave a pointer dangling, but an
// index still names the same entry.
std::map<TxnId, std::size_t> last_;
};

The journal is the heart of the design. Each withdrawal is a short run of entries, one per stage, and the last entry of each says what to do next. The stage is written before each step whose effect the ATM cannot see, so that after a power cut at any point the last entry names the step that may or may not have happened.

The stages of one withdrawal in the journal, and who moves it on
Text description of the diagram

A withdrawal starts at holding, written before the ATM asks the bank to hold the money. From holding it goes to released if the bank refuses, or if the bank does not answer and the ATM releases the hold, and to dispensing if the hold is ok; dispensing is written before the dispenser is told to count out notes. From dispensing it goes to dispensed if every note came out, to not dispensed if nothing left the cassette, and to jammed if the dispenser stopped part way. From dispensed, a commit that the bank accepts makes it committed. From not dispensed, an accepted release makes it released. From jammed, an operator who has counted the cassette moves it to dispensed if the cash left, or to not dispensed if it is all there. Committed and released are final. An operator can also move a withdrawal left at dispensing by a crash, in the same two ways.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> holding : record, then ask the bank to hold
holding --> released : refused, or released after no answer
holding --> dispensing : hold ok, record, then dispense
dispensing --> dispensed : every note out, or operator counted
dispensing --> not_dispensed : nothing left, or operator counted
dispensing --> jammed : stopped part way
dispensed --> committed : commit ok
not_dispensed --> released : release ok
jammed --> dispensed : operator counted, the cash left
jammed --> not_dispensed : operator counted, the cash is there
committed --> [*]
released --> [*]

Read the stages by what a restarted machine knows:

Last stage What may have happened What settle does
holding the bank may or may not hold the money release (ok even if never held)
dispensing some notes, all, or none may have left nothing: waits for an operator
dispensed the customer has the cash; the hold may be committed commit (safe to repeat)
not dispensed no cash left; the hold may be released release (safe to repeat)
jammed an unknown number of notes left nothing: waits for an operator
committed done nothing
released done nothing

Every row has one answer, and none of them is a guess. That is the test of a good set of stages: if two different situations end at the same stage and need different actions, the stages are too coarse.

The Journal itself checks the shape of each run (AC-4.5): an append throws if it starts a known id again, begins a new id anywhere but holding, or follows a final stage. It does not check every step in between; finish and the stage table keep those. It keeps a map from each id to the position of its latest entry, so that append and open do not scan every entry, as a journal read from a file would rebuild on start-up.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

atm.hpp
// Each state holds only what exists in it. A session at the bank exists
// only in Ready, so no other state can keep one by mistake.
struct Idle {}; // no card: nothing to remember
struct AwaitingPin {
std::string card; // the whole card number, sent to the bank with the PIN
TimePoint last_input; // when the customer last did something, for the timeout
};
struct Ready {
std::string card;
std::string session; // the bank's name for this signed-in session
TimePoint last_input;
};
struct OutOfService {
std::string reason; // for the operator, such as "no cash"
};
// A std::variant holds exactly one of the listed types at a time, and
// knows which. Assigning a new state destroys the old one, with its data:
// moving from Ready to Idle throws the session away. std::get_if and
// std::holds_alternative ask which state it is in.
using State = std::variant<Idle, AwaitingPin, Ready, OutOfService>;
The states of the ATM in step 1 and the events that move it
Text description of the diagram

Four states. A new ATM starts in OutOfService if its journal has a withdrawal waiting for an operator or its cassette is empty, and in Idle otherwise. In Idle, insert_card moves it to AwaitingPin. In AwaitingPin, a wrong PIN with tries left keeps it there, an accepted PIN moves it to Ready, and a kept card, an unknown card, a bank that does not answer, cancel, or the timeout move it back to Idle. In Ready, a balance or a refused withdrawal keeps it in Ready; a finished withdrawal, cancel, the timeout, or a session the bank no longer knows move it to Idle; a jam, or a withdrawal that empties the cassette, moves it to OutOfService. From OutOfService, an operator’s resolve moves it to Idle if no other withdrawal waits for an operator and there is cash in the cassette.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> Idle : built, nothing waits, cash in the cassette
[*] --> OutOfService : built, a withdrawal waits, or no cash
Idle --> AwaitingPin : insert_card
AwaitingPin --> AwaitingPin : wrong PIN, tries left
AwaitingPin --> Ready : PIN accepted
AwaitingPin --> Idle : card kept, card unknown, no answer, cancel, timeout
Ready --> Ready : balance, or a withdrawal refused
Ready --> Idle : withdrawal done, cancel, timeout, session lost
Ready --> OutOfService : jam, or the last notes given
OutOfService --> Idle : resolve, nothing else waits, cash in the cassette

Each state is a struct holding only what exists in it, and State is a std::variant of them, as in The states as types. The card number exists in AwaitingPin and Ready; the bank’s session id exists only in Ready. No code can read a session in Idle, because Idle has none, and leaving Ready destroys it. INV-5 is kept by the compiler, not by care.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

atm.hpp
// What the card reader should do: nothing, give the card back, or keep it.
enum class CardAction { none, eject, retain };
// What the customer sees and gets after an event. The card comes out
// before the cash: people forget a card once they have their money.
struct Response {
std::string text;
CardAction card = CardAction::none;
Money cash{}; // presented once the card is taken; zero when no cash
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

atm.hpp
// The settings of one machine, with defaults. The demo and the tests
// write `AtmConfig{"atm-7", dollars(20), dollars(400), 30s}`, which fills
// the members in the order they are declared.
struct AtmConfig {
std::string machine_id = "atm-1";
Money note = dollars(20); // the one denomination in the cassette
Money max_withdrawal = dollars(400); // this machine's limit for one withdrawal
std::chrono::seconds timeout{30}; // a session with no input for this long ends
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

atm.hpp
// The controller of one ATM. Events come from the card reader, the PIN
// pad, and the buttons, and tick comes from a timer. One session at a
// time. Not thread-safe: one thread delivers every event.
class Atm {
public:
// Reads the journal: if a withdrawal was left where only an operator
// can finish it, the ATM starts out of service. It makes no call to
// the bank; call settle once it is built. bank, dispenser, journal,
// and clock are not owned and must outlive the Atm. Throws
// std::invalid_argument for a config with no id, a note that is not
// positive, a limit below one note, or a timeout that is not positive.
Atm(AtmConfig config, Bank& bank, CashDispenser& dispenser, Journal& journal, const Clock& clock);
// One function per event, allowed only in the state named beside it.
// In any other state it changes nothing and says "Not available now."
// (insert_card in an out-of-service machine gives the card back).
Response insert_card(const std::string& card); // Idle
Response enter_pin(const PinBlock& pin); // AwaitingPin
Response check_balance(); // Ready
Response withdraw(Money amount); // Ready
Response cancel(); // AwaitingPin or Ready
// About once a second: settles, then ends a session that has had no
// input for the timeout. The text is empty if nothing happened.
Response tick();
// Finishes every open withdrawal that software can finish: commits a
// hold whose cash left the machine, and releases one whose cash did
// not, or may never have been held. Safe to repeat. Returns how many
// withdrawals are still open.
std::size_t settle();
// For an operator who has counted the cassette after a jam, or after
// a crash while notes were being counted out. Throws
// std::invalid_argument unless id is open and waits for an operator.
void resolve(const TxnId& id, bool cash_left_machine);
// For the demo and the tests, to see which state the machine is in.
[[nodiscard]] const State& state() const noexcept { return state_; }
private:
[[nodiscard]] TxnId next_id() const;
Entry record(Entry entry, Stage stage); // appends entry at stage, now; returns it
bool finish(const Entry& last); // commits or releases; false if it could not
void end_session(); // ends the bank session, if any, and rests
[[nodiscard]] State resting_state() const;
// The four parts are held by plain pointer: the Atm uses them but does
// not own them, so it never deletes them. Pointers rather than
// reference members, which would stop an Atm from being assigned. They
// are never null: the constructor takes references and keeps their
// addresses.
AtmConfig config_;
Bank* bank_;
CashDispenser* dispenser_;
Journal* journal_;
const Clock* clock_;
State state_; // the only place the machine's state lives
};

The Atm takes events and returns a Response: what the screen says, what to do with the card, and the cash to present. It does not drive the screen or the card reader itself; something around it does that with the response. That keeps the controller testable with plain values, and keeps “card before cash” in one place: a Response with cash always ejects the card too, and the hardware layer presents them in that order.

The constructor reads the journal to decide whether to start OutOfService, but makes no call to the bank. A constructor that talked to a bank that might not answer would either throw, which leaves no machine at all, or hide a failure. Instead, the owner calls settle once the machine is built, and tick calls it again every second.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

atm.cpp
// A card goes in. Allowed only when Idle; an out-of-service machine gives
// the card straight back. std::holds_alternative<T>(state_) is true when
// the variant currently holds a T. not_now() builds the reply
// {"Not available now."}, and changes nothing.
Response Atm::insert_card(const std::string& card) {
if (std::holds_alternative<OutOfService>(state_)) return {"Out of service. Take your card.", CardAction::eject};
if (!std::holds_alternative<Idle>(state_)) return not_now();
// Replaces Idle with AwaitingPin, keeping a copy of the card number and
// the time, so the timeout counts from now.
state_ = AwaitingPin{card, clock_->now()};
return {"Enter your PIN."};
}
// The PIN, sealed, goes to the bank with the card number, and the bank's
// answer decides what happens. The Atm never sees the PIN itself.
Response Atm::enter_pin(const PinBlock& pin) {
// std::get_if gives a pointer to the AwaitingPin inside state_ if that
// is the current state, and nullptr otherwise: one line both checks
// the state and gives access to its data. The pointer is only good
// while state_ still holds an AwaitingPin.
auto* waiting = std::get_if<AwaitingPin>(&state_);
if (waiting == nullptr) return not_now();
PinReply reply = bank_->verify(waiting->card, pin);
switch (reply.result) {
case PinResult::accepted:
// The new Ready is built first, copying the card from `waiting`
// and moving the session string out of the reply; only then
// does the assignment destroy the AwaitingPin. After this line
// `waiting` points at nothing and is not used again.
state_ = Ready{waiting->card, std::move(reply.session), clock_->now()};
return {"Choose balance or withdrawal."};
case PinResult::wrong_pin:
// Stay in AwaitingPin. Only the time of the last input changes;
// the bank, not the ATM, counts the tries.
waiting->last_input = clock_->now();
// "2 tries left", or "1 try left": `?:` picks the word.
return {"Wrong PIN. " + std::to_string(reply.tries_left) + (reply.tries_left == 1 ? " try" : " tries") +
" left."};
// These end the session. resting_state() is Idle, or OutOfService if
// a withdrawal waits for an operator or the cassette is empty.
case PinResult::card_retained:
state_ = resting_state();
return {"Your card has been kept. Please call your bank.", CardAction::retain};
case PinResult::card_unknown:
state_ = resting_state();
return {"This card cannot be used here. Take your card.", CardAction::eject};
case PinResult::unavailable:
break; // falls out of the switch to the "not answering" reply below
}
// Also reached if reply.result held a value outside the enum: the safe
// answer is the same as "no answer".
state_ = resting_state();
return {"The bank is not answering. Take your card.", CardAction::eject};
}
// Asks the bank what the customer can use. No answer keeps the session
// open, so the customer can try again; any other failure (such as a
// session the bank no longer knows) ends it.
Response Atm::check_balance() {
auto* ready = std::get_if<Ready>(&state_);
if (ready == nullptr) return not_now();
ready->last_input = clock_->now(); // any input restarts the timeout
const BalanceReply reply = bank_->available(ready->session);
if (reply.status == BankStatus::ok) return {"Available: " + to_string(reply.available) + "."};
if (reply.status == BankStatus::unavailable) return {"The bank is not answering. Try again."};
end_session();
return {"Your session has ended. Take your card.", CardAction::eject};
}
// The customer gives up, before or after the PIN: the card comes back.
Response Atm::cancel() {
if (!std::holds_alternative<AwaitingPin>(state_) && !std::holds_alternative<Ready>(state_)) return not_now();
end_session();
return {"Take your card.", CardAction::eject};
}
// Called by a timer about once a second. First it finishes any open
// withdrawal that it can (settle), which is how a lost commit is sent
// again. Then it ends a session that has been idle too long.
Response Atm::tick() {
// settle returns a count that tick does not need; static_cast<void>
// says the result is ignored on purpose.
static_cast<void>(settle());
const TimePoint now = clock_->now();
// Start from "input just now", which can never time out. That is the
// answer for Idle and OutOfService, where there is no session to end.
TimePoint last_input = now;
// Each pointer is declared inside the `if` condition: the rest of the
// line runs only if it is not null, and the name exists only there.
if (const auto* waiting = std::get_if<AwaitingPin>(&state_)) last_input = waiting->last_input;
if (const auto* ready = std::get_if<Ready>(&state_)) last_input = ready->last_input;
// now - last_input is how long the customer has been silent. Under the
// timeout: nothing to do, and an empty Response (text "") says so.
if (now - last_input < config_.timeout) return {};
end_session(); // silent for the whole timeout: end it, give the card back
return {"No input for a while. Take your card.", CardAction::eject};
}

Each event starts by asking whether it is allowed in the current state, with std::get_if, and returns “Not available now.” if not (AC-1.7). A wrong PIN changes nothing but the time of the last input; the count of tries lives in the bank, and the ATM only shows what the bank says is left.

tick calls settle first. That is how a commit whose reply was lost gets sent again (AC-3.7) without any retry loop in withdraw: the entry stays at dispensed, and within a second the next tick commits it. A request the bank still does not answer is simply tried on the next tick.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

atm.cpp
// Gives the customer `amount` in notes, and makes sure the bank charges
// them exactly once if the cash left the machine, and not at all if it
// did not, whatever fails on the way. Allowed only in Ready. Every path
// returns a Response; no bank or dispenser failure escapes as an
// exception (a dispenser exception is caught and treated as a jam).
Response Atm::withdraw(Money amount) {
auto* ready = std::get_if<Ready>(&state_);
if (ready == nullptr) return not_now();
ready->last_input = clock_->now();
// Checks that need no one, in order: more than zero and whole notes
// (`%` is the remainder: 13000 % 2000 is 1000, so 130.00 is refused),
// the machine's limit, and the notes in the cassette. Each returns
// early, writes nothing to the journal, and the session stays open.
if (amount <= Money{} || amount.cents % config_.note.cents != 0) {
return {"Choose a multiple of " + to_string(config_.note) + "."};
}
if (amount > config_.max_withdrawal) {
return {"This machine gives at most " + to_string(config_.max_withdrawal) + " at a time."};
}
const std::int64_t notes = amount.cents / config_.note.cents; // 12000 / 2000 is 6
if (notes > dispenser_->notes_left()) {
return {"This machine has only " + to_string(Money{dispenser_->notes_left() * config_.note.cents}) + " left."};
}
// Write ahead: the journal names the withdrawal before the bank hears of it.
// `{next_id(), masked(ready->card), amount}` builds an Entry with a new
// id, the card's last four digits, and the amount; record stamps it
// with the stage and the time, appends it, and returns that entry.
Entry entry = record({next_id(), masked(ready->card), amount}, Stage::holding);
switch (bank_->hold(ready->session, entry.id, amount)) {
case BankStatus::ok:
break; // the money is reserved: go on to the dispenser
case BankStatus::insufficient_funds:
record(entry, Stage::released); // the bank said no: nothing is held
return {"Your account does not have enough money for that."};
// Two case labels, one action. Either way nothing is held under this
// id for this withdrawal, so it is recorded as released WITHOUT
// calling release: after a conflict, that could undo another
// request's hold. The session is not what the ATM thinks: end it.
case BankStatus::unknown:
case BankStatus::conflict:
record(entry, Stage::released);
end_session();
return {"Your session has ended. Take your card.", CardAction::eject};
case BankStatus::unavailable:
// The hold may have arrived. Release it; if that fails too,
// the entry stays at holding and settle releases it later.
// finish sees the stage holding and sends a release.
static_cast<void>(finish(entry));
end_session();
return {"The bank is not answering. Nothing was taken. Take your card.", CardAction::eject};
}
// From here the money is held. Record dispensing BEFORE moving any
// notes: a power cut during the dispense leaves this as the last
// entry, and the restarted machine knows an operator must count.
entry = record(entry, Stage::dispensing);
// Start from the worst case. If dispense throws, `how` is never
// assigned and stays jammed. static_cast<int> converts the count of
// notes to the int that dispense takes; it is at most notes_left(),
// an int, so it fits.
DispenseStatus how = DispenseStatus::jammed;
try {
how = dispenser_->dispense(static_cast<int>(notes));
} catch (...) { // `...` catches an exception of any type
// Whatever went wrong, only a count of the cassette can say
// whether notes left: treat it as a jam.
}
// Record what happened, then let finish act on it. finish(record(...))
// appends the stage first and passes the new entry to finish, so the
// journal says "dispensed" before the commit is sent.
Response response;
switch (how) {
case DispenseStatus::dispensed:
// The cash is out, so the hold must be committed. If the bank
// does not answer, the entry stays at dispensed for settle.
static_cast<void>(finish(record(entry, Stage::dispensed)));
response = {"Take your card, then your cash.", CardAction::eject, amount};
break;
case DispenseStatus::failed:
// No note left the machine: release the hold. If that fails, settle retries.
static_cast<void>(finish(record(entry, Stage::not_dispensed)));
response = {"The machine could not give cash. Nothing was taken. Take your card.", CardAction::eject};
break;
case DispenseStatus::jammed:
record(entry, Stage::jammed); // the hold stays until an operator counts
response = {"The machine could not finish. You will not pay for cash you did not get. Take your card.",
CardAction::eject};
break;
}
// Every withdrawal that got this far ends the session, whatever the
// outcome. After a jam, resting_state() is OutOfService.
end_session();
return response;
}

The order is the design:

  1. Checks that need no one. Whole notes, the limit, the cassette. They come first and write nothing, so a refused amount leaves no trace (AC-3.2).
  2. Record holding, then ask for the hold. If the bank says no (insufficient_funds), nothing is held, and the session stays open for a smaller amount. If it does not answer, the hold may or may not exist; the ATM releases it at once, and if the release does not get through either, the entry stays at holding for settle.
  3. Record dispensing, then dispense. This is the step that cannot be undone. Any exception from the driver is caught and treated as a jam (AC-3.9), because after an exception nobody knows how far the dispenser got.
  4. Record what happened, then finish. dispensed commits; not dispensed releases; jammed stops and waits for an operator.

A bank that answers unknown or conflict to a hold means the session or the id is not what the ATM thinks, a bug or a session the bank has dropped. For unknown, nothing is held under the id. For conflict, something is, but it belongs to another request, so releasing it would undo someone else’s withdrawal. Either way this withdrawal holds nothing: the ATM records it as released without calling release, and ends the session.

How this code works: Every way out of Atm::withdraw

withdraw has many returns, and each one leaves the journal, the bank, and the machine in a known state. Here they all are, for one withdrawal of 120.00 (six notes) from a signed-in session:

What happens Journal stages for the id What the customer is told Session afterwards
a check fails (say 130.00) none, and no id is used “Choose a multiple of 20.00.” stays open
hold: insufficient_funds holding, released “Your account does not have enough money for that.” stays open
hold: unknown or conflict holding, released (no release request is sent) “Your session has ended. Take your card.” ended
hold: unavailable, release ok holding, released “The bank is not answering. Nothing was taken. …” ended
hold: unavailable, release lost too holding (settle releases it later) the same ended
dispensed, commit ok holding, dispensing, dispensed, committed “Take your card, then your cash.” with 120.00 ended
dispensed, commit not answered holding, dispensing, dispensed (tick commits) the same ended
dispense failed holding, dispensing, not dispensed, released “The machine could not give cash. Nothing was taken. …” ended
jammed, or the driver threw holding, dispensing, jammed “The machine could not finish. …” ended, out of service

Three things to notice:

  1. Nothing is written until every free check has passed. The first row leaves no trace at all, so a customer who mistypes an amount does not use up an id.
  2. Every row except the first two ends the session, through end_session(), which ends the bank’s session and moves to resting_state(). That is Idle, unless a withdrawal now waits for an operator (the jam row) or the cassette has just been emptied.
  3. A failed finish never changes the answer to the customer. In the “not answered” rows the customer is told the same thing as when the bank answered, because what happened to the cash is already decided; only the bank’s bookkeeping is late, and the journal makes sure it catches up.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

atm.cpp
// The id for the next withdrawal: the machine id and the journal's count
// plus one, padded to six digits. With one withdrawal already started,
// atm-7 gets "atm-7-000002". The count comes from the journal, so it
// carries on after a restart instead of starting again at 1.
TxnId Atm::next_id() const {
std::string number = std::to_string(journal_->started() + 1);
// insert(0, count, '0') puts that many '0' characters at the front:
// "2" becomes "000002".
if (number.size() < 6) number.insert(0, 6 - number.size(), '0');
return config_.machine_id + "-" + number;
}
// Appends a copy of `entry` at `stage`, stamped with the time now, and
// returns that copy so the caller can build the next stage from it. The
// parameter is a copy already (taken by value), so the caller's entry is
// not changed. Throws if the journal refuses the entry (a bug).
Entry Atm::record(Entry entry, Stage stage) {
entry.stage = stage;
entry.at = clock_->now();
journal_->append(entry);
return entry;
}
// The only code that commits or releases. It looks at nothing but the
// stage of the withdrawal's latest entry, so it does the same right thing
// straight after a step, after a restart, or after an operator's count:
// dispensed -> commit, then record committed
// holding or not dispensed -> release, then record released
// anything else -> nothing (final, or waiting for an operator)
// Returns true if the bank said ok and the final stage was recorded, and
// false otherwise; the entry then stays open, and the next settle tries
// again. Both requests are safe to repeat, so trying again is harmless.
bool Atm::finish(const Entry& last) {
if (last.stage == Stage::dispensed) {
if (bank_->commit(last.id) != BankStatus::ok) return false;
record(last, Stage::committed);
return true;
}
if (last.stage == Stage::holding || last.stage == Stage::not_dispensed) {
if (bank_->release(last.id) != BankStatus::ok) return false;
record(last, Stage::released);
return true;
}
return false; // final already, or waiting for an operator
}
// Tries finish on every open withdrawal, then counts what is still open.
// journal_->open() returns a new vector of copies, and that temporary
// vector lives until the loop ends, so finish can append to the journal
// while the loop runs without disturbing it.
std::size_t Atm::settle() {
for (const Entry& entry : journal_->open()) static_cast<void>(finish(entry));
return journal_->open().size();
}
// The operator has counted. Finds the open entry for `id` that waits for
// an operator, records what the count found (the cash left: dispensed;
// it did not: not dispensed), and lets finish commit or release. Then,
// if the machine was out of service, it works out its state again: it
// stays out of service if another withdrawal still waits or the cassette
// is empty.
void Atm::resolve(const TxnId& id, bool cash_left_machine) {
for (const Entry& entry : journal_->open()) {
// `continue` skips to the next entry: not this id, or this id but
// at a stage software can finish itself.
if (entry.id != id || !needs_operator(entry.stage)) continue;
static_cast<void>(finish(record(entry, cash_left_machine ? Stage::dispensed : Stage::not_dispensed)));
if (std::holds_alternative<OutOfService>(state_)) state_ = resting_state();
return; // done: only one entry per id is open
}
// The loop found nothing: the id is unknown, final, or not waiting
// for an operator. That is a mistake by the caller, so it throws.
throw std::invalid_argument("no withdrawal waits for an operator under " + id);
}
// Ends the bank's session if there is one (only Ready has a session),
// then moves to the resting state. Safe in any state.
void Atm::end_session() {
if (const auto* ready = std::get_if<Ready>(&state_)) bank_->end(ready->session);
state_ = resting_state();
}
// Where the machine goes when no session is running: OutOfService while
// any open withdrawal waits for an operator (the reason names the first,
// in id order) or the cassette is empty, and Idle otherwise.
State Atm::resting_state() const {
for (const Entry& entry : journal_->open()) {
if (needs_operator(entry.stage)) return OutOfService{"cash to count for " + entry.id};
}
if (dispenser_->notes_left() < 1) return OutOfService{"no cash"};
return Idle{};
}

finish is the only code that commits or releases, and it decides from the stage alone. It is called right after each step, by settle after a restart, and by resolve after an operator counts. Because every bank request it makes is safe to repeat, it does not matter how many of those calls reach the bank for the same withdrawal.

next_id numbers from journal_->started(), the count of withdrawals the journal has ever seen. A restarted machine therefore carries on from the next number, and an id is never used twice (AC-4.3). The number is zero-padded to six digits, so ids sort in the order they started, which is the order open returns them.

resting_state is where the machine goes when a session ends: out of service if any withdrawal waits for an operator or the cassette is empty, otherwise idle.

How this code works: finish, settle, and resolve on the demo's jam

The step 1 demo ends with a jam, a restart, and an operator. Here is what each of these functions does with withdrawal atm-7-000003 (100.00, five notes, every note still inside):

  1. The jam. withdraw records jammed and does not call finish: the 100.00 stays on hold. end_session calls resting_state, which finds the open jammed entry, so the state becomes OutOfService{"cash to count for atm-7-000003"}.
  2. The restart. A new Atm is built on the same journal. Its constructor calls resting_state too, and starts out of service for the same reason. It does not call the bank.
  3. settle. journal_->open() returns one entry, at jammed. finish matches neither dispensed nor holding/not dispensed, so it returns false without a request. settle then counts the open entries again: 1, which the demo prints as “1 still open”.
  4. resolve("atm-7-000003", false). The loop finds the entry, and needs_operator(jammed) is true. With false (“no cash left”), record appends not dispensed, and finish sees that stage and sends release. The bank answers ok, so finish appends released. The machine was OutOfService, so resting_state runs again: nothing waits now and 42 notes are left, so it is Idle.

The journal for that id now reads holding, dispensing, jammed, not dispensed, released, and the bank holds 0.00. Had the release been lost, the entry would have stayed at not dispensed, and the next settle would have sent it again. Note that settle and resolve both loop over journal_->open(), which is a new vector of copies, so the appends made inside the loop cannot disturb it.

Rule Where it lives
Which events are allowed when the state types, and the get_if at the top of each event
Whether a PIN is right, and when to keep a card the bank
The order of steps in a withdrawal Atm::withdraw
What each stage means after a crash finish, needs_operator, and the Stage comments
When to commit and when to release Atm::finish, and nowhere else
Every request is safe to repeat the Bank contract, keyed by TxnId
Ids never repeat next_id, from Journal::started
No second start, nothing after a final stage Journal::append
When the machine is out of service resting_state
What the ATM may know about a PIN or card PinBlock and masked

Take the second withdrawal in the step 1 demo: the customer takes out 40.00, the bank commits it, and the reply to the commit is lost.

A withdrawal whose commit reply is lost, finished by the next tick
Text description of the diagram

The customer asks to withdraw 40.00. The ATM appends atm-7-000002 at holding to the journal, then asks the bank to hold 40.00 under that id in session s-2; the bank says ok. The ATM appends dispensing and tells the dispenser to count out two notes; the dispenser reports dispensed. The ATM appends dispensed and sends a commit. The bank commits, but the reply is lost, so the ATM sees unavailable. The withdrawal stays at dispensed, and the customer gets the card and then the 40.00. A second later, tick calls settle, which asks the journal for open withdrawals and gets atm-7-000002 at dispensed. It sends the commit again; the bank answers ok, because the id is already committed, and the ATM appends committed.

Diagram source (Mermaid)
sequenceDiagram
participant C as customer
participant A as Atm
participant J as Journal
participant B as Bank
participant D as dispenser
C->>A: withdraw(40.00)
A->>J: append atm-7-000002 holding
A->>B: hold(s-2, atm-7-000002, 40.00)
B-->>A: ok
A->>J: append dispensing
A->>D: dispense(2)
D-->>A: dispensed
A->>J: append dispensed
A->>B: commit(atm-7-000002)
Note over B: commits, then the reply is lost
B-->>A: unavailable
A-->>C: card out, then cash 40.00
Note over A: one second later
A->>A: tick, then settle
A->>J: open()
J-->>A: atm-7-000002 dispensed
A->>B: commit(atm-7-000002)
B-->>A: ok, already committed
A->>J: append committed

Step by step, in the code:

  1. withdraw(dollars(40)) finds Ready, passes the three checks (two notes, under 400.00, 44 notes left), and next_id gives atm-7-000002, because the journal has seen one withdrawal.
  2. record(..., Stage::holding) appends; then hold returns ok.
  3. record(entry, Stage::dispensing) appends; then dispense(2) returns dispensed.
  4. finish(record(entry, Stage::dispensed)) appends dispensed and calls commit. The fake bank commits and returns unavailable, so finish returns false and appends nothing.
  5. The response ejects the card and presents 40.00. The bank balance is already 140.00, but the journal still shows one open withdrawal.
  6. tick calls settle, which calls finish on the open dispensed entry. commit returns ok, committed is appended, and the journal has nothing open. The balance is still 140.00: one charge.

Now put a power cut at each arrow. Before holding is written, there is no withdrawal at all. After holding, settle releases a hold that may exist. After dispensing, the machine starts out of service and an operator counts. After dispensed, settle commits. There is no point at which a restart leaves the customer paying for nothing or getting something for nothing, and no point at which it leaves a decision to chance.

Hold-dispense-commit fixes the order. It does not survive a power cut.

Two details make the journal work, and both are easy to miss. The entry must be written before the step, not after: an entry written after dispense would be lost by a power cut during it, and the restarted machine would not know that notes may have moved. And every request that settle sends must be safe to repeat, because a restart cannot know whether the request it is about to send was already sent.

The stages dispensing and jammed are different from the others: no request to the bank can settle them, because the question is about paper, not data. How many notes left the machine? The design answers it by not answering it: the machine goes out of service, keeps the hold, and waits for an operator to count and call resolve. Keeping the hold is what keeps FR-4 either way. If the cash left, the hold is committed; if not, released; and in the meantime the customer cannot spend money that may already be in their hand.

A design that guessed (say, “a jam usually gives nothing, so release”) would be right most of the time and wrong in the worst way the rest. When a fact is unknowable to the program, make it a state that waits for someone who can know it.

The same thinking applies to the card number, less strictly: the Atm needs the whole number for the length of a session, to send to the bank, so it keeps it in the session’s state and nowhere else. The journal, which lasts, keeps only the last four digits.

Why not the State pattern, with an AtmState interface and a class per state? The states here differ in their data (a card, a session) much more than in their behaviour, and most events are allowed in one state only. A variant puts each event’s whole logic in one function, where the order of steps in a withdrawal can be read top to bottom. The State pattern pays off when each state has a lot of its own behaviour for many events; here it would spread withdraw over four classes, three of which say “not now”.

The id is the machine id plus a number, so it is unique across machines only if machine ids are. The step 2 tests met this the hard way: two ATMs in one test were both atm-7, and their holds collided at the bank. The fix was to name the second one atm-8, and the assumption is now stated in Scope.

  • No State pattern classes. The variant, for the reasons above.
  • No retry loop. A request that fails stays in the journal, and tick calls settle every second. The schedule is the journal.
  • No refund. A hold is released, not refunded, because nothing was ever taken. Refunds exist only where money was taken first.
  • No exceptions for bank failures. “No answer” is a result. The only exceptions are for programming errors: a bad config, a hold for zero, a journal entry after a final stage, an unknown id passed to resolve.
  • No thread. One thread delivers every event (NFR-4). A device call blocks that thread, which is what a single-customer machine does anyway.

The example has two steps, each a complete program with its own tests:

  • Step 1 is the design above: sessions, PINs, balance, withdrawal, the journal, and recovery.
  • Step 2 is the change: a daily limit and deposits. See When the requirements change.

The order inside step 1 is worth copying. The fake bank and the fake dispenser came first, each with its failure switches, and the tests of the bank’s own contract (AC-4.6), because every later test trusts them. Then the session states and their events, with no money at all. Then a withdrawal that only worked when nothing failed, then the journal and settle, and then each failure, one test at a time, from the table of stages.

The demo signs in after one wrong PIN, takes out 120.00, takes out 40.00 with the commit reply lost, and then has the dispenser jam with every note still inside. Then the machine restarts, and an operator counts.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The composition root owns everything, and declares each object
// before the objects that refer to it.
// Local objects are destroyed in reverse order, so the two Atms
// (declared after their parts) go first, while the bank, dispenser,
// journal, and clock they point at still exist.
constexpr unsigned pin_key = 0x5a; // shared by the toy PIN pad and the fake bank
// 2 March 2026, 09:00: sys_days is a date, and + 9h adds nine hours.
ManualClock clock(sys_days{year{2026} / 3 / 2} + 9h);
FakeBank bank(pin_key);
FakeDispenser dispenser(50); // 50 notes of 20.00
Journal journal;
const std::string card = "4000001234567899";
bank.open_account(card, "4321", dollars(300));
// id, note, limit, timeout. 30s is 30 seconds (std::chrono literal).
const AtmConfig config{"atm-7", dollars(20), dollars(400), 30s};
Atm machine(config, bank, dispenser, journal, clock);
static_cast<void>(machine.settle()); // at start-up: nothing to finish yet
// show prints the event's name and the response. One wrong PIN, then
// the right one, a balance, a refused amount, and a good withdrawal.
show("insert card", machine.insert_card(card));
show("enter 1111", machine.enter_pin(toy::seal("1111", pin_key)));
show("enter 4321", machine.enter_pin(toy::seal("4321", pin_key)));
show("balance", machine.check_balance());
// `{13000}` is Money{13000}, that is 130.00: not whole 20.00 notes.
show("withdraw 130.00", machine.withdraw({13000}));
show("withdraw 120.00", machine.withdraw(dollars(120)));
show_bank(bank, card);
std::cout << "the bank's reply to the next commit is lost:\n";
// true: the bank commits, then the reply is lost, so the ATM sees
// unavailable and the entry stays at dispensed.
bank.fail_next(BankCall::commit, true);
static_cast<void>(machine.insert_card(card));
static_cast<void>(machine.enter_pin(toy::seal("4321", pin_key)));
show("withdraw 40.00", machine.withdraw(dollars(40)));
std::cout << " journal: " << journal.open().size() << " open, " << journal.open().front().id << " "
<< to_string(journal.open().front().stage) << "\n";
// One second later the timer ticks; tick calls settle, which sends the
// commit again. The bank says ok, because the id is already committed.
clock.advance(1s);
static_cast<void>(machine.tick());
std::cout << " after a tick: " << journal.open().size() << " open\n";
show_bank(bank, card);
std::cout << "the dispenser jams, with every note still inside:\n";
dispenser.fail_next(DispenseStatus::jammed, 0); // a jam with 0 notes out
static_cast<void>(machine.insert_card(card));
static_cast<void>(machine.enter_pin(toy::seal("4321", pin_key)));
show("withdraw 100.00", machine.withdraw(dollars(100)));
show_state(machine);
show_bank(bank, card);
show("insert card", machine.insert_card(card)); // out of service: the card comes back
// A second Atm on the same journal plays the machine after a reboot.
// (The first one still exists but is not used again.)
std::cout << "the ATM restarts on the same journal:\n";
Atm restarted(config, bank, dispenser, journal, clock);
std::cout << " settle: " << restarted.settle() << " still open\n";
show_state(restarted);
std::cout << "an operator counts the cassette; the notes are all there:\n";
// false: no cash left the machine, so the 100.00 hold is released.
restarted.resolve("atm-7-000003", false);
show_state(restarted);
show_bank(bank, card);
std::cout << "cash given out: " << dispenser.presented() << " notes, " << dispenser.notes_left() << " left\n";
Expected output
insert card: Enter your PIN.
enter 1111: Wrong PIN. 2 tries left.
enter 4321: Choose balance or withdrawal.
balance: Available: 300.00.
withdraw 130.00: Choose a multiple of 20.00.
withdraw 120.00: Take your card, then your cash. [card out] [cash 120.00]
bank: balance 180.00, on hold 0.00
the bank's reply to the next commit is lost:
withdraw 40.00: Take your card, then your cash. [card out] [cash 40.00]
journal: 1 open, atm-7-000002 dispensed
after a tick: 0 open
bank: balance 140.00, on hold 0.00
the dispenser jams, with every note still inside:
withdraw 100.00: The machine could not finish. You will not pay for cash you did not get. Take your card. [card out]
atm: out of service (cash to count for atm-7-000003)
bank: balance 140.00, on hold 100.00
insert card: Out of service. Take your card. [card out]
the ATM restarts on the same journal:
settle: 1 still open
atm: out of service (cash to count for atm-7-000003)
an operator counts the cassette; the notes are all there:
atm: idle
bank: balance 140.00, on hold 0.00
cash given out: 8 notes, 42 left

Read the output against the rules:

  • 130.00 is not whole notes and is refused before the bank hears of it.
  • The lost commit: the cash comes out, the journal shows one open withdrawal at dispensed, and the next tick finishes it. The balance falls by 40.00, once.
  • The jam: the customer pays nothing yet, the 100.00 stays on hold, and the machine is out of service. The next card is returned at once.
  • The restart: the new machine’s constructor calls resting_state, finds the jammed withdrawal, and starts out of service. settle cannot finish it and reports 1 still open.
  • The operator counts the cassette, finds every note, and calls resolve with “no cash left the machine”. The hold is released and the machine is idle again.
  • 8 notes went out: six for 120.00 and two for 40.00.

The tests are named after the acceptance criteria and run against the real Atm and Journal, with the fake bank and dispenser. A World builds everything in the order the machine needs it, and can restart the machine on the same journal.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// Everything an ATM needs, declared before the ATM. restart destroys the
// ATM and builds a new one on the same journal, bank, and cassette, as a
// power cut and a reboot would.
// Its members are built in the order they are declared, top to bottom,
// and destroyed in the reverse order. So the clock, bank, cassette, and
// journal exist before the Atm that keeps pointers to them, and outlive
// it. The Atm is held in a std::unique_ptr, an owning pointer that deletes
// its object when it is reset or itself destroyed, so the world can throw
// one Atm away and build another.
struct World {
ManualClock clock{start};
FakeBank bank{key};
// No count here: the constructor below gives it one, dispenser(notes).
FakeDispenser dispenser;
Journal journal;
// Machine "atm-7", 20.00 notes, at most 400.00 at a time, a 30-second timeout.
AtmConfig config{"atm-7", dollars(20), dollars(400), 30s};
std::unique_ptr<Atm> machine;
// By default a cassette of 50 notes (1,000.00) and an account with
// 300.00 for `card`, PIN "4321". The account is opened before the
// first Atm is built.
explicit World(int notes = 50, Money balance = dollars(300)) : dispenser(notes) {
bank.open_account(card, "4321", balance);
restart();
}
// A power cut and a reboot. reset() destroys the old Atm first, so it
// is gone before the new one starts; make_unique then builds a new Atm,
// whose constructor reads the journal as a rebooted ATM would. The
// bank, cassette, journal, and clock all survive.
void restart() {
machine.reset();
machine = std::make_unique<Atm>(config, bank, dispenser, journal, clock);
}
// The current machine. Call it again after restart: a reference kept
// from before would refer to the destroyed Atm.
Atm& atm() { return *machine; }
// Inserts the card and enters the right PIN.
// static_cast<void>(...) says the Response is ignored on purpose.
void sign_in() {
static_cast<void>(atm().insert_card(card));
static_cast<void>(atm().enter_pin(toy::seal("4321", key)));
}
// The stages one withdrawal went through, in the order they were
// written: the journal's entries for that id only. Tests compare it with
// a list such as holding, dispensing, dispensed, committed.
[[nodiscard]] std::vector<Stage> stages(const TxnId& id) const {
std::vector<Stage> result;
for (const Entry& entry : journal.entries()) {
if (entry.id == id) result.push_back(entry.stage);
}
return result;
}
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// LLD_TEST(name) defines one test function and registers it, so the test
// runner calls it. LLD_CHECK(condition) records a failure, with the file
// and line, if the condition is false, and the test carries on.
// LLD_CHECK_EQ(actual, expected) does the same for `actual == expected`,
// and also prints both values; the operator<< overloads at the top of this
// file let it print Money, Stage, CardAction, and BankStatus. They come
// from the site's small test header, lld_test.hpp.
//
// in<S>(machine), a helper defined above this excerpt, is true when the
// machine's state is currently an `S`, using std::holds_alternative:
// `in<Ready>(w.atm())` asks "is it Ready?".
//
// AC-1.1: a known card and the right PIN ("4321", sealed with the test
// key) move the machine from Idle to AwaitingPin to Ready, and open
// exactly one session at the bank.
LLD_TEST(ac_1_1_a_card_and_the_right_pin_open_a_session) {
World w;
LLD_CHECK_EQ(w.atm().insert_card(card).text, std::string("Enter your PIN."));
LLD_CHECK(in<AwaitingPin>(w.atm()));
const Response response = w.atm().enter_pin(toy::seal("4321", key));
LLD_CHECK_EQ(response.card, CardAction::none);
LLD_CHECK(in<Ready>(w.atm()));
LLD_CHECK_EQ(w.bank.open_sessions(), std::size_t{1});
}
// AC-1.2: the bank, not the ATM, counts wrong PINs. Two wrong PINs at the
// world's ATM and a third at a second ATM (same bank and clock, its own
// journal and cassette) reach the bank's limit of three, so the second ATM
// keeps the card. After that the card is blocked, and the bank keeps it
// even with the right PIN.
LLD_TEST(ac_1_2_wrong_pins_are_counted_by_the_bank_across_atms) {
World w;
Journal other_journal;
FakeDispenser other_cassette(10);
AtmConfig other_config = w.config;
other_config.machine_id = "atm-8"; // machine ids are unique: the bank keys holds by them
Atm other(other_config, w.bank, other_cassette, other_journal, w.clock);
static_cast<void>(w.atm().insert_card(card));
LLD_CHECK_EQ(w.atm().enter_pin(toy::seal("1111", key)).text, std::string("Wrong PIN. 2 tries left."));
LLD_CHECK_EQ(w.atm().enter_pin(toy::seal("2222", key)).text, std::string("Wrong PIN. 1 try left."));
// Cancel ends this attempt; the bank still remembers the two wrong tries.
static_cast<void>(w.atm().cancel());
// The third wrong PIN, at another ATM, still keeps the card.
static_cast<void>(other.insert_card(card));
const Response kept = other.enter_pin(toy::seal("3333", key));
LLD_CHECK_EQ(kept.card, CardAction::retain);
LLD_CHECK(in<Idle>(other));
// And now even the right PIN keeps it.
static_cast<void>(w.atm().insert_card(card));
LLD_CHECK_EQ(w.atm().enter_pin(toy::seal("4321", key)).card, CardAction::retain);
}
// AC-1.2, the other half: two wrong PINs and then the right one reset the
// bank's count to zero. So in a new session, one wrong PIN leaves 2 tries;
// without the reset it would have been the third, and the card kept.
LLD_TEST(ac_1_2_the_right_pin_resets_the_count) {
World w;
static_cast<void>(w.atm().insert_card(card));
static_cast<void>(w.atm().enter_pin(toy::seal("1111", key)));
static_cast<void>(w.atm().enter_pin(toy::seal("1111", key)));
static_cast<void>(w.atm().enter_pin(toy::seal("4321", key)));
static_cast<void>(w.atm().cancel());
static_cast<void>(w.atm().insert_card(card));
LLD_CHECK_EQ(w.atm().enter_pin(toy::seal("1111", key)).text, std::string("Wrong PIN. 2 tries left."));
}
// AC-1.3: a card the bank has blocked is kept (CardAction::retain) even
// with its right PIN; a card number the bank has never heard of is given
// back (eject). Either way the machine goes back to Idle.
LLD_TEST(ac_1_3_a_blocked_card_is_kept_and_an_unknown_one_returned) {
World w;
w.bank.open_account("5000000000000001", "1234", dollars(10));
w.bank.block("5000000000000001");
static_cast<void>(w.atm().insert_card("5000000000000001"));
LLD_CHECK_EQ(w.atm().enter_pin(toy::seal("1234", key)).card, CardAction::retain);
static_cast<void>(w.atm().insert_card("6000000000000002"));
LLD_CHECK_EQ(w.atm().enter_pin(toy::seal("1234", key)).card, CardAction::eject);
LLD_CHECK(in<Idle>(w.atm()));
}
// AC-1.4: fail_next(BankCall::verify) makes the bank's next verify answer
// unavailable without doing anything (applied defaults to false). The ATM
// cannot sign the customer in, so it gives the card back and goes to Idle.
LLD_TEST(ac_1_4_a_bank_that_does_not_answer_returns_the_card) {
World w;
w.bank.fail_next(BankCall::verify);
static_cast<void>(w.atm().insert_card(card));
const Response response = w.atm().enter_pin(toy::seal("4321", key));
LLD_CHECK_EQ(response.card, CardAction::eject);
LLD_CHECK(in<Idle>(w.atm()));
}
// AC-1.5: cancel gives the card back and ends the session at the bank, so
// open_sessions falls back to 0. Cancel also works while the machine is
// still waiting for the PIN.
LLD_TEST(ac_1_5_cancel_returns_the_card_and_ends_the_bank_session) {
World w;
w.sign_in();
LLD_CHECK_EQ(w.atm().cancel().card, CardAction::eject);
LLD_CHECK(in<Idle>(w.atm()));
LLD_CHECK_EQ(w.bank.open_sessions(), std::size_t{0});
static_cast<void>(w.atm().insert_card(card));
LLD_CHECK_EQ(w.atm().cancel().card, CardAction::eject); // before the PIN, too
}
// AC-1.6: the 30-second timeout, checked to the second with the
// ManualClock. 29 seconds after signing in, tick does nothing (an empty
// text). Any input starts the count again. At exactly 30 seconds with no
// input, tick ends the session: `now - last_input < timeout` is false at
// 30. The same timeout applies while the machine waits for a PIN.
LLD_TEST(ac_1_6_a_session_with_no_input_ends_after_the_timeout) {
World w;
w.sign_in();
w.clock.advance(29s);
LLD_CHECK(w.atm().tick().text.empty());
static_cast<void>(w.atm().check_balance()); // input: the 30 s start again
w.clock.advance(29s);
LLD_CHECK(w.atm().tick().text.empty());
w.clock.advance(1s);
LLD_CHECK_EQ(w.atm().tick().card, CardAction::eject);
LLD_CHECK(in<Idle>(w.atm()));
LLD_CHECK_EQ(w.bank.open_sessions(), std::size_t{0});
static_cast<void>(w.atm().insert_card(card)); // waiting for a PIN times out too
w.clock.advance(30s);
LLD_CHECK_EQ(w.atm().tick().card, CardAction::eject);
}
// AC-1.7: an event the current state does not allow is answered "Not
// available now." and changes nothing. In Idle: withdraw, balance, PIN,
// and cancel. In Ready: a second card and a second PIN. The machine stays
// where it was, and nothing reaches the journal.
LLD_TEST(ac_1_7_an_event_in_the_wrong_state_changes_nothing) {
World w;
LLD_CHECK_EQ(w.atm().withdraw(dollars(20)).text, std::string("Not available now."));
LLD_CHECK_EQ(w.atm().check_balance().text, std::string("Not available now."));
LLD_CHECK_EQ(w.atm().enter_pin(toy::seal("4321", key)).text, std::string("Not available now."));
LLD_CHECK_EQ(w.atm().cancel().text, std::string("Not available now."));
LLD_CHECK(in<Idle>(w.atm()));
w.sign_in();
LLD_CHECK_EQ(w.atm().insert_card(card).text, std::string("Not available now."));
LLD_CHECK_EQ(w.atm().enter_pin(toy::seal("4321", key)).text, std::string("Not available now."));
LLD_CHECK(in<Ready>(w.atm()));
LLD_CHECK(w.journal.entries().empty());
}
// AC-1.8: the sealed PIN block does not contain the digits, and seal
// refuses a PIN of 3 digits, of 7 digits, or with a letter in it. After a
// withdrawal, every journal entry shows only "****7899", the card's last
// four digits. LLD_CHECK_THROWS(expression, type) runs the expression and
// records a failure unless it throws an exception of that type.
LLD_TEST(ac_1_8_no_pin_and_no_whole_card_number_is_kept) {
World w;
const PinBlock pin = toy::seal("4321", key);
// find returns std::string::npos, meaning "not found", when the text is not there.
LLD_CHECK(pin.sealed().find("4321") == std::string::npos);
LLD_CHECK_THROWS(toy::seal("123", key), std::invalid_argument);
LLD_CHECK_THROWS(toy::seal("1234567", key), std::invalid_argument);
LLD_CHECK_THROWS(toy::seal("12a4", key), std::invalid_argument);
w.sign_in();
static_cast<void>(w.atm().withdraw(dollars(20)));
for (const Entry& entry : w.journal.entries()) {
LLD_CHECK_EQ(entry.card, std::string("****7899"));
}
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// AC-3.1: the path where nothing fails. 120.00 is six 20.00 notes. The
// card comes out and the cash is presented; the dispenser gave 6 notes;
// the bank took 120.00 (300.00 - 120.00 = 180.00) and holds nothing; the
// journal shows the four stages of a finished withdrawal; and the session
// is over.
LLD_TEST(ac_3_1_a_withdrawal_returns_the_card_gives_the_cash_and_commits) {
World w;
w.sign_in();
const Response response = w.atm().withdraw(dollars(120));
LLD_CHECK_EQ(response.card, CardAction::eject);
LLD_CHECK_EQ(response.cash, dollars(120));
LLD_CHECK_EQ(w.dispenser.presented(), 6);
LLD_CHECK_EQ(w.bank.balance(card), dollars(180));
LLD_CHECK_EQ(w.bank.held(card), Money{});
// The extra brackets around the std::vector are needed: the preprocessor
// would otherwise split the macro's argument at the commas in the braces.
LLD_CHECK(w.stages("atm-7-000001") ==
(std::vector<Stage>{Stage::holding, Stage::dispensing, Stage::dispensed, Stage::committed}));
LLD_CHECK(in<Idle>(w.atm()));
LLD_CHECK_EQ(w.bank.open_sessions(), std::size_t{0});
}
// AC-3.2: amounts the machine cannot give are refused before the bank
// hears of them. World(5) loads only 5 notes, 100.00. 25.00 is not whole
// notes; zero and -20.00 are not positive; 420.00 is past this machine's
// 400.00 limit; 120.00 is six notes, one more than the cassette holds.
// The session stays open, and the journal is still empty: nothing is
// written for a refused amount.
LLD_TEST(ac_3_2_an_amount_the_machine_cannot_give_is_refused_before_the_bank) {
World w(5); // 100.00 in the cassette
w.sign_in();
LLD_CHECK_EQ(w.atm().withdraw(Money{2500}).text, std::string("Choose a multiple of 20.00."));
LLD_CHECK_EQ(w.atm().withdraw(Money{}).text, std::string("Choose a multiple of 20.00."));
LLD_CHECK_EQ(w.atm().withdraw(dollars(-20)).text, std::string("Choose a multiple of 20.00."));
LLD_CHECK_EQ(w.atm().withdraw(dollars(420)).text, std::string("This machine gives at most 400.00 at a time."));
LLD_CHECK_EQ(w.atm().withdraw(dollars(120)).text, std::string("This machine has only 100.00 left."));
LLD_CHECK(in<Ready>(w.atm()));
LLD_CHECK(w.journal.entries().empty());
}
// AC-3.3: 320.00 is more than the 300.00 in the account. The bank answers
// insufficient_funds, so nothing is held; the journal records the attempt
// as holding, then released; the session stays Ready; and a smaller
// amount, 300.00, then goes through under a new id, atm-7-000002.
LLD_TEST(ac_3_3_not_enough_money_holds_nothing_and_keeps_the_session) {
World w;
w.sign_in();
LLD_CHECK_EQ(w.atm().withdraw(dollars(320)).text,
std::string("Your account does not have enough money for that."));
LLD_CHECK(in<Ready>(w.atm()));
LLD_CHECK(w.stages("atm-7-000001") == (std::vector<Stage>{Stage::holding, Stage::released}));
LLD_CHECK_EQ(w.atm().withdraw(dollars(300)).cash, dollars(300));
}
// AC-3.4: the hold gets no answer, in both ways a network can lose it.
// The loop runs the test twice: applied = false means the request was lost
// on the way there (the bank did nothing); true means the bank made the
// hold and only the reply was lost. Either way the ATM releases the id at
// once (release is ok even for an id the bank never saw), gives no cash,
// and ends the session with the card out. The journal: holding, released.
LLD_TEST(ac_3_4_a_hold_the_bank_does_not_answer_is_released) {
for (const bool applied : {false, true}) { // lost on the way there, or on the way back
World w;
w.sign_in();
w.bank.fail_next(BankCall::hold, applied);
const Response response = w.atm().withdraw(dollars(100));
LLD_CHECK_EQ(response.cash, Money{});
LLD_CHECK_EQ(response.card, CardAction::eject);
LLD_CHECK_EQ(w.bank.held(card), Money{});
LLD_CHECK_EQ(w.dispenser.presented(), 0);
LLD_CHECK(w.stages("atm-7-000001") == (std::vector<Stage>{Stage::holding, Stage::released}));
}
}
// AC-3.5: the hold arrives (only its reply is lost), and the release the
// ATM sends at once gets no answer either. So 100.00 is still held and the
// withdrawal stays open at holding. Software can finish that, so the
// machine stays in service. The next tick calls settle, which sends the
// release again; this time it works, and nothing is held or open.
LLD_TEST(ac_3_5_a_release_the_bank_does_not_answer_is_settled_later) {
World w;
w.sign_in();
w.bank.fail_next(BankCall::hold, true);
// A failure of another kind is kept apart: the fake keeps one waiting per kind.
w.bank.fail_next(BankCall::release);
static_cast<void>(w.atm().withdraw(dollars(100)));
LLD_CHECK_EQ(w.bank.held(card), dollars(100));
LLD_CHECK_EQ(w.journal.open().size(), std::size_t{1});
LLD_CHECK(in<Idle>(w.atm())); // software can finish this one, so the ATM stays in service
static_cast<void>(w.atm().tick());
LLD_CHECK_EQ(w.bank.held(card), Money{});
LLD_CHECK(w.journal.open().empty());
}
// AC-3.6: the dispenser fails before the first note (failed). No cash
// left, so the hold is released and the customer pays nothing: the balance
// stays 300.00, and the journal shows not dispensed, then released.
LLD_TEST(ac_3_6_a_dispenser_that_gives_nothing_releases_the_hold) {
World w;
w.sign_in();
w.dispenser.fail_next(DispenseStatus::failed);
const Response response = w.atm().withdraw(dollars(100));
LLD_CHECK_EQ(response.cash, Money{});
LLD_CHECK_EQ(w.bank.balance(card), dollars(300));
LLD_CHECK_EQ(w.bank.held(card), Money{});
LLD_CHECK(w.stages("atm-7-000001") ==
(std::vector<Stage>{Stage::holding, Stage::dispensing, Stage::not_dispensed, Stage::released}));
}
// AC-3.7: the commit is applied at the bank, but its reply is lost. The
// customer gets 100.00 and is charged (300.00 to 200.00), but the ATM saw
// "unavailable", so the entry stays open at dispensed. The next tick
// settles it: the commit is sent again, the bank answers ok without taking
// the money twice, and committed is written. The extra settle finds
// nothing to do. The balance stays 200.00: charged once.
LLD_TEST(ac_3_7_a_lost_commit_reply_charges_once) {
World w;
w.sign_in();
w.bank.fail_next(BankCall::commit, true);
LLD_CHECK_EQ(w.atm().withdraw(dollars(100)).cash, dollars(100)); // the customer has the cash
LLD_CHECK_EQ(w.bank.balance(card), dollars(200)); // and the bank did commit
// open() returns a copy of the open entries. .at(0) checks the index
// and would throw, not read past the end, if the copy were empty.
const std::vector<Entry> open = w.journal.open();
LLD_CHECK_EQ(open.at(0).stage, Stage::dispensed); // but the ATM does not know
static_cast<void>(w.atm().tick());
static_cast<void>(w.atm().settle());
LLD_CHECK_EQ(w.bank.balance(card), dollars(200)); // committed again: still charged once
LLD_CHECK(w.journal.open().empty());
}
// AC-3.8: the dispenser jams with no notes out (fail_next's count defaults
// to 0, and the ATM cannot see it anyway). The customer gets the card and
// no cash; the 100.00 stays held and is not taken; the machine goes out of
// service and turns the next card away; and settle cannot finish the
// withdrawal, so it reports 1 still open and the hold stays.
LLD_TEST(ac_3_8_a_jam_keeps_the_hold_and_takes_the_atm_out_of_service) {
World w;
w.sign_in();
w.dispenser.fail_next(DispenseStatus::jammed);
const Response response = w.atm().withdraw(dollars(100));
LLD_CHECK_EQ(response.card, CardAction::eject);
LLD_CHECK_EQ(response.cash, Money{});
LLD_CHECK(in<OutOfService>(w.atm()));
LLD_CHECK_EQ(w.bank.held(card), dollars(100));
LLD_CHECK_EQ(w.bank.balance(card), dollars(300));
LLD_CHECK_EQ(w.atm().insert_card(card).card, CardAction::eject);
LLD_CHECK_EQ(w.atm().settle(), std::size_t{1}); // settle cannot finish it
LLD_CHECK_EQ(w.bank.held(card), dollars(100));
}
// AC-3.9: a dispenser driver that throws. Broken is a dispenser made for
// this one test, as a class inside the function: it says it has 10 notes
// and throws from every dispense (its parameter has no name because it is
// not used). A second Atm is built on it, sharing the world's bank,
// journal, and clock. That Atm catches the exception and treats it as a
// jam: no cash, out of service, and the open entry is at jammed.
LLD_TEST(ac_3_9_a_dispenser_that_throws_is_treated_as_a_jam) {
class Broken final : public CashDispenser {
public:
[[nodiscard]] int notes_left() const noexcept override { return 10; }
[[nodiscard]] DispenseStatus dispense(int) override { throw std::runtime_error("driver crashed"); }
};
World w;
Broken broken;
Atm machine(w.config, w.bank, broken, w.journal, w.clock);
static_cast<void>(machine.insert_card(card));
static_cast<void>(machine.enter_pin(toy::seal("4321", key)));
LLD_CHECK_EQ(machine.withdraw(dollars(40)).cash, Money{});
LLD_CHECK(in<OutOfService>(machine));
const std::vector<Entry> open = w.journal.open();
LLD_CHECK_EQ(open.at(0).stage, Stage::jammed);
}
// AC-3.10: a cassette of 3 notes and a withdrawal of 60.00, all three. The
// withdrawal succeeds, and then the machine is out of service with the
// reason "no cash". std::get<OutOfService> reads the state as that type;
// it would throw std::bad_variant_access if the state were anything else,
// which the check on the line before rules out.
LLD_TEST(ac_3_10_the_last_notes_take_the_atm_out_of_service) {
World w(3);
w.sign_in();
LLD_CHECK_EQ(w.atm().withdraw(dollars(60)).cash, dollars(60));
LLD_CHECK(in<OutOfService>(w.atm()));
LLD_CHECK_EQ(std::get<OutOfService>(w.atm().state()).reason, std::string("no cash"));
}

Most failure tests check what the customer was told and what the bank holds and has taken, and many also check the exact list of stages in the journal. The stages are the strongest check. Two designs can give the same balance at the end of a test while one of them would lose money after a power cut in the middle; only the journal tells them apart.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// A crash can stop the ATM after any journal entry. Each case writes the
// journal and the bank as the crash left them, restarts, and settles.
//
// AC-4.1: four crash points that software can finish. Each Case names the
// last stage written, whether the hold reached the bank, and the balance
// expected after settle:
// holding, hold at the bank -> release it: still 300.00
// holding, hold never arrived -> release anyway, ok for an unseen id: 300.00
// not dispensed, hold at the bank -> release it: 300.00
// dispensed, hold at the bank -> commit it: 200.00
// The test plays the old machine by hand: it signs in at the bank directly
// (bank.verify), makes the hold, and appends the entries a crash would
// have left. Then restart builds a new Atm on that journal.
LLD_TEST(ac_4_1_after_a_crash_settle_finishes_what_software_can) {
struct Case {
Stage last;
bool hold_reached_bank;
Money balance_after;
};
// Each `c` is a copy of one Case from the brace list.
for (const Case c : {Case{Stage::holding, true, dollars(300)}, Case{Stage::holding, false, dollars(300)},
Case{Stage::not_dispensed, true, dollars(300)}, Case{Stage::dispensed, true, dollars(200)}}) {
World w;
// The crashed machine's session; kept to send a late hold below.
const PinReply signed_in = w.bank.verify(card, toy::seal("4321", key));
if (c.hold_reached_bank) {
LLD_CHECK_EQ(w.bank.hold(signed_in.session, "atm-7-000001", dollars(100)), BankStatus::ok);
}
// An Entry is {id, masked card, amount, stage, time}. A withdrawal
// that got past holding wrote dispensing before its last stage.
w.journal.append({"atm-7-000001", "****7899", dollars(100), Stage::holding, start});
if (c.last != Stage::holding) w.journal.append({"atm-7-000001", "****7899", dollars(100), Stage::dispensing, start});
if (c.last != Stage::holding) w.journal.append({"atm-7-000001", "****7899", dollars(100), c.last, start});
// None of these stages needs an operator, so the new machine starts
// Idle, and settle finishes the withdrawal and reports 0 still open.
w.restart();
LLD_CHECK(in<Idle>(w.atm()));
LLD_CHECK_EQ(w.atm().settle(), std::size_t{0});
LLD_CHECK_EQ(w.bank.balance(card), c.balance_after);
LLD_CHECK_EQ(w.bank.held(card), Money{});
if (!c.hold_reached_bank) {
// A hold that arrives after the release must not reserve money.
// The release left a released record for the id at the bank, so
// the late hold is a conflict.
LLD_CHECK_EQ(w.bank.hold(signed_in.session, "atm-7-000001", dollars(100)), BankStatus::conflict);
LLD_CHECK_EQ(w.bank.held(card), Money{});
}
}
}
// AC-4.2: a crash after dispensing was written. Nobody knows how many
// notes left, so the restarted machine starts out of service, settle
// cannot finish it (1 still open), and the 100.00 stays held. An operator
// counts and calls resolve: cash_left true commits (balance 200.00), false
// releases (300.00). Either way nothing is held and the machine is Idle.
LLD_TEST(ac_4_2_a_crash_while_dispensing_waits_for_an_operator) {
for (const bool cash_left : {true, false}) {
World w;
const PinReply signed_in = w.bank.verify(card, toy::seal("4321", key));
LLD_CHECK_EQ(w.bank.hold(signed_in.session, "atm-7-000001", dollars(100)), BankStatus::ok);
w.journal.append({"atm-7-000001", "****7899", dollars(100), Stage::holding, start});
w.journal.append({"atm-7-000001", "****7899", dollars(100), Stage::dispensing, start});
w.restart();
LLD_CHECK(in<OutOfService>(w.atm()));
LLD_CHECK_EQ(w.atm().settle(), std::size_t{1});
LLD_CHECK_EQ(w.bank.held(card), dollars(100));
w.atm().resolve("atm-7-000001", cash_left);
LLD_CHECK(in<Idle>(w.atm()));
LLD_CHECK_EQ(w.bank.balance(card), cash_left ? dollars(200) : dollars(300));
LLD_CHECK_EQ(w.bank.held(card), Money{});
}
}
// AC-4.3: ids never repeat. One 20.00 withdrawal, a restart, and another.
// The new Atm numbers from journal.started(), so the second withdrawal is
// atm-7-000002, each id has its own four entries, and both were charged:
// 300.00 - 40.00 = 260.00. A counter kept in memory would have started
// again at atm-7-000001.
LLD_TEST(ac_4_3_ids_never_repeat_after_a_restart) {
World w;
w.sign_in();
static_cast<void>(w.atm().withdraw(dollars(20)));
w.restart();
w.sign_in();
static_cast<void>(w.atm().withdraw(dollars(20)));
LLD_CHECK_EQ(w.stages("atm-7-000001").size(), std::size_t{4});
LLD_CHECK_EQ(w.stages("atm-7-000002").size(), std::size_t{4});
LLD_CHECK_EQ(w.bank.balance(card), dollars(260));
}
// AC-4.4: resolve is only for a withdrawal that waits for an operator. A
// finished (committed) withdrawal and an id that never existed both throw
// std::invalid_argument, and the balance stays at 280.00.
LLD_TEST(ac_4_4_resolve_accepts_only_a_withdrawal_that_waits_for_an_operator) {
World w;
w.sign_in();
static_cast<void>(w.atm().withdraw(dollars(20)));
LLD_CHECK_THROWS(w.atm().resolve("atm-7-000001", true), std::invalid_argument); // committed
LLD_CHECK_THROWS(w.atm().resolve("atm-7-000999", true), std::invalid_argument); // unknown
LLD_CHECK_EQ(w.bank.balance(card), dollars(280));
}
// AC-4.5: the Journal on its own checks the shape of each run. A new id
// that starts at dispensing throws; holding is accepted; a second holding
// for the same id throws; released is accepted (append checks the start
// and the end of a run, not each step between); and nothing may follow a
// final stage, so committed after released throws. One withdrawal was
// started, and none is open.
LLD_TEST(ac_4_5_the_journal_refuses_entries_out_of_order) {
Journal journal;
LLD_CHECK_THROWS(journal.append({"a-1", "****1", dollars(20), Stage::dispensing, start}), std::invalid_argument);
journal.append({"a-1", "****1", dollars(20), Stage::holding, start});
LLD_CHECK_THROWS(journal.append({"a-1", "****1", dollars(20), Stage::holding, start}), std::invalid_argument);
journal.append({"a-1", "****1", dollars(20), Stage::released, start});
LLD_CHECK_THROWS(journal.append({"a-1", "****1", dollars(20), Stage::committed, start}), std::invalid_argument);
LLD_CHECK_EQ(journal.started(), std::size_t{1});
LLD_CHECK(journal.open().empty());
}
// AC-4.6: the fake bank keeps the Bank contract, which every other test
// trusts. With id t-1: a repeated hold reserves 50.00 once; commit twice
// takes 50.00 once (300.00 to 250.00); release after commit is a conflict.
// With t-2: release twice is ok; commit after release is a conflict, and
// the balance is still 250.00. A commit of t-3, never held, is unknown.
LLD_TEST(ac_4_6_the_bank_makes_commit_and_release_safe_to_repeat) {
FakeBank bank(key);
bank.open_account(card, "4321", dollars(300));
const PinReply signed_in = bank.verify(card, toy::seal("4321", key));
LLD_CHECK_EQ(bank.hold(signed_in.session, "t-1", dollars(50)), BankStatus::ok);
LLD_CHECK_EQ(bank.hold(signed_in.session, "t-1", dollars(50)), BankStatus::ok); // a repeat
LLD_CHECK_EQ(bank.held(card), dollars(50));
LLD_CHECK_EQ(bank.commit("t-1"), BankStatus::ok);
LLD_CHECK_EQ(bank.commit("t-1"), BankStatus::ok);
LLD_CHECK_EQ(bank.balance(card), dollars(250));
LLD_CHECK_EQ(bank.release("t-1"), BankStatus::conflict);
LLD_CHECK_EQ(bank.hold(signed_in.session, "t-2", dollars(50)), BankStatus::ok);
LLD_CHECK_EQ(bank.release("t-2"), BankStatus::ok);
LLD_CHECK_EQ(bank.release("t-2"), BankStatus::ok);
LLD_CHECK_EQ(bank.commit("t-2"), BankStatus::conflict);
LLD_CHECK_EQ(bank.balance(card), dollars(250));
LLD_CHECK_EQ(bank.commit("t-3"), BankStatus::unknown);
}

ac_4_1 writes a journal as a crash would leave it at each stage that software can finish (holding with and without the hold at the bank, not dispensed, and dispensed), restarts, and checks that settle does the one right thing for each. For the hold that never arrived, it then sends that hold late and checks that the bank refuses it. ac_4_2 does the same for dispensing, and checks that the machine starts out of service.

A random run. The last test makes 4,000 random steps: sessions, withdrawals, failures of every kind from the bank and the dispenser, time passing, restarts, and an operator who counts truthfully.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// Random sessions, withdrawals, failures of every kind, restarts, and an
// operator who counts the cassette truthfully. At the end, no money is
// lost or made: the account fell by exactly the cash that came out.
LLD_TEST(inv_money_leaves_the_account_only_as_cash) {
// A pseudo-random generator with a fixed seed, 2026: every run makes the
// same 4,000 steps, so a failure can be repeated and debugged. pick(n)
// is a small lambda that returns a number from 0 to n - 1; [&] lets it
// use `random` by reference, so each call moves the generator on.
std::mt19937 random(2026);
auto pick = [&](int n) { return static_cast<int>(random() % static_cast<unsigned>(n)); };
// A large cassette (5,000 notes) and balance, so many withdrawals can go through.
World w(5000, dollars(100000));
// For each withdrawal set up to jam: true if its notes left the machine.
std::map<TxnId, bool> cash_out_by_jam; // what the operator will find
for (int step = 0; step < 4000; ++step) {
// Nine kinds of step, picked at random: 0 cancel; 1 sign in, then
// withdraw; 2 withdraw (refused unless a session is open); 3 make
// the bank's next call of a random kind fail, applied or not; 4 let
// 0 to 39 seconds pass, then tick; 5 restart; 6 the operator counts
// every jam; 7 ask for the balance; 8 (default) settle.
switch (pick(9)) {
case 0: static_cast<void>(w.atm().cancel()); break;
// [[fallthrough]] says that running on into case 2 is meant.
case 1: w.sign_in(); [[fallthrough]];
case 2: {
// 1 to 20 notes (20.00 to 400.00). How it ends: 0 the dispenser
// fails, 1 it jams with nothing out, 2 it jams with every note
// out, 3 to 9 it works.
const auto before = w.journal.started();
const int notes = 1 + pick(20);
const int how = pick(10);
if (how == 0) w.dispenser.fail_next(DispenseStatus::failed);
if (how == 1) w.dispenser.fail_next(DispenseStatus::jammed, 0);
if (how == 2) w.dispenser.fail_next(DispenseStatus::jammed, notes);
static_cast<void>(w.atm().withdraw(dollars(20 * notes)));
// If a new withdrawal started (started() grew) and a jam was set
// up, remember what the operator will find. The journal's last
// entry belongs to this withdrawal. One that set up a jam but
// never reached the dispenser leaves a map entry never used.
if (w.journal.started() > before && (how == 1 || how == 2)) {
cash_out_by_jam[w.journal.entries().back().id] = how == 2;
}
// Setting the next ending to dispensed, the normal one, clears a
// failure this withdrawal did not use (it was refused before the
// dispenser), so a leftover jam cannot hit a later withdrawal
// whose id is not in the map.
w.dispenser.fail_next(DispenseStatus::dispensed); // a failure not used is cleared
break;
}
// static_cast<BankCall>(pick(5)) turns 0 to 4 into one of the five
// kinds of call: verify, available, hold, commit, release.
case 3: w.bank.fail_next(static_cast<BankCall>(pick(5)), pick(2) == 1); break;
case 4: w.clock.advance(seconds{pick(40)}); static_cast<void>(w.atm().tick()); break;
case 5: w.restart(); break;
// journal.open() returns a copy, so resolve can append to the
// journal while the loop walks the copy. In this test, only jams
// wait for an operator (restarts happen between steps, never in
// the middle of a dispense), and each jam is in the map; .at would
// throw if one were not.
case 6:
for (const Entry& entry : w.journal.open()) {
if (needs_operator(entry.stage)) w.atm().resolve(entry.id, cash_out_by_jam.at(entry.id));
}
break;
case 7: static_cast<void>(w.atm().check_balance()); break;
default: static_cast<void>(w.atm().settle()); break;
}
// Holds on the bank are never more than the open withdrawals.
// Every held amount must belong to a withdrawal the journal still
// has open, or money would be stuck at the bank with nothing to
// finish it. It may be less: an open holding whose hold never
// arrived holds nothing, and an open dispensed one may already be
// committed. `open` starts at zero.
Money open;
for (const Entry& entry : w.journal.open()) open = open + entry.amount;
LLD_CHECK(w.bank.held(card) <= open);
}
// At most one failure of each kind can be waiting, and a settle uses up
// any commit or release failure it meets, so after a few settles none
// is left to stop one. Then an operator finishes the rest.
for (int i = 0; i < 3; ++i) static_cast<void>(w.atm().settle());
for (const Entry& entry : w.journal.open()) {
if (needs_operator(entry.stage)) w.atm().resolve(entry.id, cash_out_by_jam.at(entry.id));
}
static_cast<void>(w.atm().settle());
// Nothing is open, nothing is held, and the account fell by exactly
// 20.00 (2,000 cents) for each note the dispenser presented. The count
// is widened to std::int64_t before multiplying, to match Money's cents.
LLD_CHECK(w.journal.open().empty());
LLD_CHECK_EQ(w.bank.held(card), Money{});
LLD_CHECK_EQ(w.bank.balance(card), dollars(100000) - Money{std::int64_t{2000} * w.dispenser.presented()});
LLD_CHECK(w.journal.started() > 50); // the run did withdraw
}
How this code works: The step 1 random run
  1. A repeatable dice. std::mt19937 random(2026) is a pseudo-random generator with a fixed seed, so every run makes the same 4,000 steps, and a failure can be replayed exactly. pick(n) gives a whole number from 0 to n - 1.
  2. One random step at a time. Each step is one of nine things: cancel; sign in and withdraw; withdraw (refused unless a session is open); arm a bank failure of a random kind, applied or not; let 0 to 39 seconds pass and tick; restart; let the operator count every jam; ask for the balance; or settle.
  3. Each withdrawal decides its ending in advance: one time in ten the dispenser fails, one in ten it jams with nothing out, one in ten it jams with every note out, and otherwise it works.
  4. The operator knows the truth. For each withdrawal set up to jam, cash_out_by_jam records whether its notes left. That is what an honest count of the cassette would find, and what resolve is told.
  5. The checks, after every step and at the end, are described just below. The per-step check allows the bank to hold less than the open withdrawals: a hold that never arrived holds nothing, and a commit whose reply was lost is no longer held.

After every step, the bank must not hold more than the open withdrawals. At the end, after a few settles and the operator, nothing is open, nothing is held, and the balance has fallen by exactly 20.00 for every note the dispenser gave out. Any order of failures and restarts that charged twice, or not at all, would break that last check.

Checking the tests. The tests were checked by 8 hand-written mutations of the step 1 code, applied one at a time by a script to a scratch copy (the script is not part of the example): committing a not dispensed hold, leaving dispensing out of the operator stages, not recording released after a release, numbering ids from a counter that starts again on a restart, letting an exception from the dispenser escape, skipping the release after a hold with no answer, treating a jam as “nothing left”, and never timing out. Each made at least one test fail.

“Two things from the business. Cards need a daily cash limit, 500 by default, and a fraudster with a copied card should not get round it by going from machine to machine. And our new machines take deposits: the customer puts notes in, sees the total, and confirms.”

Two new rules:

  • FR-8 Daily limit. Each card may take out at most its daily limit in one day, at every ATM together. Money held and then released does not count. The balance shows what is left today.
  • FR-9 Deposit. In a session, the customer puts notes in the slot. The machine takes them into an escrow, shows the total, and waits for confirm or cancel. On confirm, the notes go into the store and the account is credited. On cancel or the timeout, the notes come back. FR-4 extends: the account is credited exactly for the notes that reached the store.

“At every ATM together” decides where the limit lives. An ATM sees only its own withdrawals; only the bank sees all of them. So the limit is a rule of the bank, checked when it is asked to hold, and the ATM only reports it.

The deposit is the more interesting one. Read the money flow backwards and it is a withdrawal: an irreversible movement of paper, with a bank request before it that can be undone and one after it that can be repeated.

UC-6 Keep to the daily limit.

  • AC-6.1 A withdrawal past the daily limit is refused, nothing is held, and the session stays open for a smaller amount.
  • AC-6.2 The limit counts every ATM: 400.00 at one machine leaves 100.00 at another.
  • AC-6.3 Money held and then released (a failed dispense, a bank with no answer) does not count.
  • AC-6.4 The limit starts again at midnight, by the bank’s clock, and not a minute before.
  • AC-6.5 The balance shows what is left today.

UC-7 Deposit cash.

  • AC-7.1 A deposit is stored, then credited, and the stages are expecting, storing, stored, committed.
  • AC-7.2 Cancel or the timeout gives the notes back, writes nothing to the journal, and leaves the balance as it was.
  • AC-7.3 No notes accepted keeps the session; while notes are in escrow, other events wait.
  • AC-7.4 A bank that does not answer the announcement gives the notes back.
  • AC-7.5 Notes the store does not take go back, and nothing is credited.
  • AC-7.6 A credit with no answer, whether or not the bank applied it, is sent again and credits once.
  • AC-7.7 A store jam waits for an operator.
  • AC-7.8 After a crash, settle finishes a deposit that software can.
  • AC-7.9 An acceptor that throws is treated as a jam.
  • AC-7.10 A deposit does not count toward the limit, and does not raise it.

AC-7.10 is a business rule worth asking about rather than guessing. The team’s answer: the limit is on cash going out, so depositing 200.00 does not let a card take out 700.00 today.

File Change
bank.hpp BankStatus::limit_exceeded; BalanceReply::left_today; a new request, expect; commit and release also finish a deposit
fake_bank.* a clock; a daily limit per account; taken_today; holds and expected deposits share one table
note_acceptor.hpp new: NoteAcceptor, with escrow, and FakeAcceptor
journal.* five deposit stages; needs_operator and is_start know them
atm.* a Depositing state; deposit and confirm; finish commits stored and releases expecting and not stored
tests the step 1 tests pass the acceptor and the bank’s clock, and expect the longer balance text; otherwise unchanged

The journal’s design and the way ids are made did not change, and settle, resolve, and finish changed only by learning the five new stages. That is what a good stage table buys: a new kind of operation is new rows, not new machinery.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

bank.hpp
// The ATM's id for one movement of money: the machine's id and a
// sequence number, such as "atm-7-000042". The bank keys holds by it,
// which makes commit and release safe to repeat after a lost reply or a
// restart.
using TxnId = std::string;
// What the bank says about a card and a PIN. Unchanged from step 1.
enum class PinResult {
accepted,
wrong_pin, // tries_left says how many are left
card_retained, // too many wrong PINs, or a blocked card: keep the card
card_unknown, // not a card this bank knows
unavailable, // no answer
};
// The whole answer to verify. Each member starts with a safe default, so
// `return {};` means "no answer" and `{PinResult::card_unknown}` fills in
// only the first member. Only some members mean something for each result.
struct PinReply {
PinResult result = PinResult::unavailable;
std::string session{}; // when accepted: names this card's session at the bank
int tries_left = 0; // when wrong_pin
};
// The answer to every request about money. Step 2 adds limit_exceeded.
// unavailable is the one to think hardest about: the request may have
// been done and only the reply lost, so the ATM must be able to send it
// again safely.
enum class BankStatus {
ok,
insufficient_funds, // a hold for more than is available
limit_exceeded, // a hold that would take this card past its daily limit
unknown, // no such session, or no such transaction
conflict, // the transaction already ended the other way
unavailable, // no answer: the request may or may not have been applied
};
// The answer to available: a status, and two amounts when it is ok.
struct BalanceReply {
BankStatus status = BankStatus::unavailable;
Money available{}; // the balance less the money on hold, when ok
Money left_today{}; // how much more this card may take out today, when ok
};
// The ATM's view of its bank. Network failures are answers
// (unavailable), not exceptions; an implementation throws only for a
// programming error, such as a hold for zero. An interface (every function
// is `= 0`): FakeBank implements it for the demo and the tests, and a real
// network client would implement it in production.
class Bank {
public:
virtual ~Bank() = default;
// The bank counts wrong PINs per card, across every ATM, and says
// when the ATM must keep the card.
[[nodiscard]] virtual PinReply verify(const std::string& card, const PinBlock& pin) = 0;
// The money the customer can use now, and what is left of today's
// limit. Needs the session that an accepted verify returned.
[[nodiscard]] virtual BalanceReply available(const std::string& session) = 0;
// Reserves amount under id. A repeat with the same id and amount is
// ok and reserves nothing more. A hold for an id already released is
// a conflict, so a hold that arrives late cannot reserve money again.
// The bank keeps the daily limit: a card's holds and withdrawals on
// one day, at every ATM, may not pass it. A released hold does not
// count.
[[nodiscard]] virtual BankStatus hold(const std::string& session, const TxnId& id, Money amount) = 0;
// Announces a deposit under id. Nothing is credited until commit. A
// repeat and a late arrival are treated as for hold. It is the deposit's
// version of hold: the step before the notes move, which the bank can
// still refuse and the ATM can still undo with release.
[[nodiscard]] virtual BankStatus expect(const std::string& session, const TxnId& id, Money amount) = 0;
// Takes the held money for good, or credits the expected deposit.
// Safe to repeat.
[[nodiscard]] virtual BankStatus commit(const TxnId& id) = 0;
// Gives the held money back, or forgets the expected deposit. Safe to
// repeat, and ok for an id the bank has never seen: the request that
// the ATM sent may not have arrived. A conflict after a commit.
[[nodiscard]] virtual BankStatus release(const TxnId& id) = 0;
// Closes a session. noexcept and no result: ending a session must
// always "work" from the ATM's side, even if the message is lost.
virtual void end(const std::string& session) noexcept = 0;
protected:
// Only derived classes may build or copy a Bank.
Bank() = default;
Bank(const Bank&) = default;
Bank& operator=(const Bank&) = default;
};

The limit is in the bank’s contract, so every bank the ATM talks to must keep it, and the ATM’s only change is to say so: limit_exceeded from a hold records the withdrawal as released and tells the customer, and the session stays open, as for not enough money.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

fake_bank.hpp
// A stand-in for the bank's side, for the demo and the tests. It keeps
// accounts, counts wrong PINs, and keeps holds by transaction id, as the
// Bank contract says. It can be told to fail its next call of one kind,
// either before doing anything or after (the reply is lost). A day is a
// calendar day in UTC, read from the clock.
// Names one kind of request, so a test can say which one to fail.
enum class BankCall { verify, available, hold, expect, commit, release };
class FakeBank final : public Bank {
public:
// The third wrong PIN with no right one in between keeps the card.
static constexpr int max_tries = 3;
// clock is not owned and must outlive the bank. It is the bank's own
// clock: the bank, not the ATM, decides when a day starts. pin_key must
// be the key the PIN pad (toy::seal) used, or no PIN matches.
FakeBank(unsigned pin_key, const Clock& clock) : pin_key_(pin_key), clock_(&clock) {}
// Test set-up. open_account throws std::invalid_argument for a card
// that already has an account; the daily limit is 500.00 unless given.
// block marks a card as blocked, so the next verify keeps it.
void open_account(const std::string& card, std::string pin, Money balance, Money daily_limit = dollars(500));
void block(const std::string& card) { accounts_.at(card).blocked = true; }
// The next call of this kind returns unavailable. With applied, it
// does its work first, so only the reply is lost.
// Each switch fails exactly one call: the next call of that kind uses
// it up. Setting it again for the same kind replaces it.
void fail_next(BankCall call, bool applied = false) { failures_[call] = applied; }
// For checks in tests. held is the withdrawals still on hold, and
// expected the deposits announced but not yet credited or released.
[[nodiscard]] Money balance(const std::string& card) const { return accounts_.at(card).balance; }
[[nodiscard]] Money held(const std::string& card) const;
[[nodiscard]] Money expected(const std::string& card) const;
// Held and committed withdrawals today: what counts toward the limit.
[[nodiscard]] Money taken_today(const std::string& card) const;
[[nodiscard]] std::size_t open_sessions() const noexcept { return sessions_.size(); }
[[nodiscard]] PinReply verify(const std::string& card, const PinBlock& pin) override;
[[nodiscard]] BalanceReply available(const std::string& session) override;
[[nodiscard]] BankStatus hold(const std::string& session, const TxnId& id, Money amount) override;
[[nodiscard]] BankStatus expect(const std::string& session, const TxnId& id, Money amount) override;
[[nodiscard]] BankStatus commit(const TxnId& id) override;
[[nodiscard]] BankStatus release(const TxnId& id) override;
// Erasing a session that is not there does nothing, so this is safe to
// repeat, and it cannot throw.
void end(const std::string& session) noexcept override { sessions_.erase(session); }
private:
// One customer's account: their PIN (kept here, at the "bank", never in
// the Atm), money, daily limit, and the count of wrong PINs in a row.
struct Account {
std::string pin;
Money balance;
Money daily_limit;
int wrong = 0;
bool blocked = false;
};
// One table holds both kinds of request, told apart by `deposit`. Each
// starts held and ends committed (money taken, or credited) or released
// (nothing moves), and never moves on from either. A release for an id
// never seen makes one that is released from the start.
enum class HoldState { held, committed, released };
struct Hold {
std::string card; // empty for a release of an id never held
Money amount;
HoldState state = HoldState::held;
bool deposit = false; // an expected deposit, not a hold on money
std::chrono::sys_days day{}; // the day it was made: it counts toward that day
};
// True if this call must fail; then applied says whether to do it first.
bool failing(BankCall call, bool& applied);
// hold and expect, which differ only in the checks before a new entry.
BankStatus reserve(BankCall call, const std::string& session, const TxnId& id, Money amount, bool deposit);
// Today's date: floor<days> rounds the time down to midnight (UTC), so
// 23:59 and 00:01 on the next day give different days.
[[nodiscard]] std::chrono::sys_days today() const { return std::chrono::floor<std::chrono::days>(clock_->now()); }
// Each std::map is a sorted table from a key to a value. Keeping holds_
// by TxnId is what makes a repeat recognisable: the same id finds the
// same entry, so it is not reserved twice.
unsigned pin_key_;
const Clock* clock_;
std::map<std::string, Account> accounts_; // card -> account
std::map<std::string, std::string> sessions_; // session -> card
std::map<TxnId, Hold> holds_;
std::map<BankCall, bool> failures_; // the fail_next switches still waiting
int next_session_ = 1; // sessions are named "s-1", "s-2", ...
};

The fake bank counts a card’s withdrawals for the day: held or committed, not released, and not deposits. It checks the funds first and the limit second, so a customer who has neither hears about the money. The day comes from the bank’s clock, not the ATM’s: machines in different places, or with clocks that drift, would otherwise disagree about when a day starts.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

note_acceptor.hpp
// How a store ended, as the hardware reports it: the deposit's version of
// DispenseStatus.
enum class StoreStatus {
stored, // every note in escrow moved into the store
failed, // nothing moved: the notes are still in escrow
jammed, // stopped part way: how many notes reached the store is not known
};
// The deposit module's driver, as the ATM sees it. Notes wait in escrow,
// where they can still be given back, until store moves them into the
// store, from which they cannot. One denomination, the same as the
// cassette; deposited notes are not given out again. An interface, like
// CashDispenser: FakeAcceptor implements it here.
class NoteAcceptor {
public:
virtual ~NoteAcceptor() = default;
// Takes the notes in the slot into escrow, and returns how many it
// accepted. Notes it cannot read go straight back.
[[nodiscard]] virtual int take_in() = 0;
// Moves the notes in escrow into the store. A note that reaches the
// store cannot be given back; after `failed` they are all still in
// escrow, and after `jammed` nobody knows where each one is.
[[nodiscard]] virtual StoreStatus store() = 0;
// Gives the notes in escrow back to the customer.
virtual void give_back() = 0;
protected:
// As for the other interfaces: only derived classes may build or copy one.
NoteAcceptor() = default;
NoteAcceptor(const NoteAcceptor&) = default;
NoteAcceptor& operator=(const NoteAcceptor&) = default;
};

The escrow is what makes cancel possible. Notes in escrow have been counted but not yet taken; give_back returns them. store moves them somewhere they cannot come back from, and, like the dispenser, it can jam with an unknown number moved.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

note_acceptor.hpp
// A stand-in for the hardware. put is the customer putting notes in the
// slot. It can be told how its next store ends. It counts notes in four
// places, slot -> escrow -> store (or back to the customer), so a test can
// check where every note went.
class FakeAcceptor final : public NoteAcceptor {
public:
// Adds notes to the slot; they are not counted until take_in. Throws
// std::invalid_argument for a negative count.
void put(int notes) {
if (notes < 0) throw std::invalid_argument("cannot put in fewer than no notes");
slot_ += notes;
}
// For a jam, notes_in says how many notes reached the store before it
// stopped; the rest are stuck in the machine. The ATM cannot see it.
// Only the next store: store() clears the setting once used.
void fail_next(StoreStatus how, int notes_in = 0) {
next_ = how;
jam_in_ = notes_in;
}
[[nodiscard]] int in_store() const noexcept { return stored_; }
[[nodiscard]] int given_back() const noexcept { return returned_; }
[[nodiscard]] int in_escrow() const noexcept { return escrow_; }
// Everything in the slot moves to escrow. The fake reads every note,
// so none goes straight back. Returns the total now in escrow.
[[nodiscard]] int take_in() override {
escrow_ += slot_;
slot_ = 0;
return escrow_;
}
// Same pattern as FakeDispenser::dispense: the outcome a test chose,
// or "stored" if none, used once.
[[nodiscard]] StoreStatus store() override {
const StoreStatus how = next_.value_or(StoreStatus::stored);
next_.reset();
if (how == StoreStatus::failed) return how; // nothing moved: the notes stay in escrow
// Stored: every note in escrow arrives. Jammed: only jam_in_ do.
const int in = how == StoreStatus::stored ? escrow_ : jam_in_;
if (in > escrow_) throw std::invalid_argument("a jam cannot store more notes than were in escrow");
stored_ += in;
escrow_ = 0; // after a jam, the rest are stuck: not in escrow, not given back
return how;
}
// Escrow empties into the customer's hand.
void give_back() override {
returned_ += escrow_;
escrow_ = 0;
}
private:
int slot_ = 0; // put in by the customer, not yet taken in
int escrow_ = 0; // counted, and can still go back
int stored_ = 0; // in the store for good, ever
int returned_ = 0; // given back to customers, ever
std::optional<StoreStatus> next_; // empty: the next store works
int jam_in_ = 0; // notes that reach the store in the next jam
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

atm.hpp
// Each state holds only what exists in it. A session at the bank exists
// only in Ready and Depositing, so no other state can keep one by mistake.
struct Idle {}; // no card: nothing to remember
struct AwaitingPin {
std::string card; // the whole card number, sent to the bank with the PIN
TimePoint last_input; // when the customer last did something, for the timeout
};
struct Ready {
std::string card;
std::string session; // the bank's name for this signed-in session
TimePoint last_input;
};
struct Depositing { // notes in escrow, waiting for confirm or cancel
std::string card;
std::string session; // still open: confirm needs it to tell the bank
int notes = 0; // notes now in escrow (the amount is notes times the note's value)
TimePoint last_input;
};
struct OutOfService {
std::string reason; // for the operator, such as "no cash"
};
// A std::variant holds exactly one of the listed types at a time, and
// knows which. Assigning a new state destroys the old one, with its data.
// Step 2 adds one alternative, Depositing; each event still begins by
// asking, with std::get_if or std::holds_alternative, which state it is in.
using State = std::variant<Idle, AwaitingPin, Ready, Depositing, OutOfService>;

Depositing holds the card, the session, and the count of notes in escrow. Only Ready and Depositing hold a session now, and the variant still makes sure that nothing else can.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

atm.cpp
// The first half of a deposit: count the notes into escrow and show the
// total. Nothing is written to the journal and the bank hears nothing
// yet, because nothing has happened that cannot be undone: cancel or the
// timeout just gives the notes back. Allowed only in Ready.
Response Atm::deposit() {
auto* ready = std::get_if<Ready>(&state_);
if (ready == nullptr) return not_now();
ready->last_input = clock_->now();
const int notes = acceptor_->take_in();
if (notes < 1) return {"No notes were accepted."}; // stays in Ready
const Money amount{notes * config_.note.cents}; // 7 notes of 20.00: 14000 cents
// Ready becomes Depositing. The card and session strings are moved
// (not copied) out of Ready into the new state; the new Depositing is
// built before the assignment destroys the Ready, so the moves are
// safe, and `ready` must not be used after this line.
state_ = Depositing{std::move(ready->card), std::move(ready->session), notes, clock_->now()};
return {"You put in " + to_string(amount) + ". Confirm or cancel."};
}
// The second half: the customer said yes. The same three moves as a
// withdrawal, in the same order: a request the bank can refuse (expect),
// the step that cannot be undone (store), then commit or release, which
// are safe to repeat. Every way out ends the session. Allowed only in
// Depositing.
Response Atm::confirm() {
auto* depositing = std::get_if<Depositing>(&state_);
if (depositing == nullptr) return not_now();
const Money amount{depositing->notes * config_.note.cents};
// Write ahead, as for a withdrawal: the bank hears of the deposit
// before the notes move, and the journal before the bank.
Entry entry = record({next_id(), masked(depositing->card), amount}, Stage::expecting);
switch (bank_->expect(depositing->session, entry.id, amount)) {
case BankStatus::ok:
break; // the bank expects it: go on to the store
case BankStatus::unavailable:
// finish sees expecting and sends a release; if that is lost
// too, the entry stays at expecting and settle tries again.
static_cast<void>(finish(entry)); // it may have arrived: release it
acceptor_->give_back();
end_session();
return {"The bank is not answering. Take your notes and your card.", CardAction::eject};
case BankStatus::unknown:
case BankStatus::conflict:
case BankStatus::insufficient_funds: // not sent for a deposit
case BankStatus::limit_exceeded: // nor this: the limit is on cash out
// All are listed so the switch names every status. The bank
// refused, or the session is not what the ATM thinks: nothing
// is expected under this id for this deposit, so it is recorded
// as released without a release request, as a withdrawal does.
record(entry, Stage::released);
acceptor_->give_back();
end_session();
return {"Your session has ended. Take your notes and your card.", CardAction::eject};
}
// The step that cannot be undone. Until it starts, the notes can go
// back; once it has, only the store knows where they are.
entry = record(entry, Stage::storing);
// Start from the worst case: if store throws, `how` stays jammed.
StoreStatus how = StoreStatus::jammed;
try {
how = acceptor_->store();
} catch (...) {
// As for the dispenser: only a count can say where the notes are.
}
Response response;
switch (how) {
case StoreStatus::stored:
// The bank is told to credit it. If it does not answer, the
// entry stays at stored, and settle asks again.
static_cast<void>(finish(record(entry, Stage::stored)));
response = {"Deposited " + to_string(amount) + ". Take your card.", CardAction::eject};
break;
case StoreStatus::failed:
// Nothing moved: the notes go back first, then the expected
// deposit is released.
acceptor_->give_back();
static_cast<void>(finish(record(entry, Stage::not_stored)));
response = {"The machine could not take your notes. Take your notes and your card.", CardAction::eject};
break;
case StoreStatus::jammed:
record(entry, Stage::store_jammed); // an operator counts the store
response = {"The machine could not finish. Your bank will credit what reached the store. Take your card.",
CardAction::eject};
break;
}
end_session(); // after a store jam, resting_state() is OutOfService
return response;
}
How this code works: deposit and confirm in the step 2 demo

The step 2 demo deposits seven notes, and the bank does not answer the credit.

  1. deposit() finds Ready, and take_in moves the seven notes from the slot to escrow and returns 7. The amount is 7 times 2000 cents, 140.00. The state becomes Depositing, and the card number and session are moved into it from Ready (the old Ready is then destroyed). Nothing is in the journal yet, and the bank knows nothing: a cancel now would just give the notes back.
  2. confirm() finds Depositing. next_id gives atm-7-000003: the journal has seen two ids already, the 400.00 withdrawal and the refused 200.00, which was recorded as holding then released.
  3. Write ahead. expecting is recorded, then expect is sent; the bank says ok.
  4. The step that cannot be undone. storing is recorded, then store moves all seven notes into the store.
  5. Credit. stored is recorded and finish sends commit. The demo made the bank fail that call before doing anything, so finish returns false and the entry stays at stored. The customer still sees “Deposited 140.00”: the notes are in the store, and the credit will follow. The session ends and the machine is Idle.
  6. The restart. The new Atm’s settle finds atm-7-000003 at stored, sends commit again, gets ok, and records committed. The balance goes from 500.00 to 640.00, once.

The order, side by side with a withdrawal:

Withdrawal Deposit Why
record holding, then hold record expecting, then expect the bank can still refuse, and nothing has moved
record dispensing, dispense record storing, then store the step that cannot be undone
dispensed, then commit stored, then commit (the credit) the money follows the paper, and can be sent again
not dispensed, then release give back, not stored, then release nothing moved
jammed: wait for an operator store jammed: wait for an operator only a count can say how much moved

Why tell the bank before storing, when nothing is debited? Because the bank can still say no: the session has expired, or the account cannot take deposits. Once the notes are in the store, a refusal from the bank would leave the customer’s money inside the machine with nowhere to credit it. Asked first, a refusal just gives the notes back.

And why not credit before storing? For the same reason a withdrawal does not commit before dispensing: the store can fail, and then the bank has credited notes the machine gave back.

The stages of one deposit in the journal: a withdrawal in reverse
Text description of the diagram

A deposit starts at expecting, written before the ATM tells the bank to expect it. From expecting it goes to released if the bank refuses, or if it does not answer and the ATM releases the expected deposit, and to storing if the bank says ok; storing is written before the acceptor moves the notes into the store. From storing it goes to stored if every note arrived, to not stored if nothing moved and the notes were given back, and to store jammed if the acceptor stopped part way. From stored, an accepted commit credits the account and makes it committed. From not stored, an accepted release makes it released. From store jammed, an operator who has counted the store moves it to stored or to not stored. Committed and released are final. An operator can also move a deposit left at storing by a crash, in the same two ways.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> expecting : record, then tell the bank
expecting --> released : refused, or released after no answer
expecting --> storing : bank ok, record, then store
storing --> stored : every note in the store, or operator counted
storing --> not_stored : nothing moved, or operator counted
storing --> store_jammed : stopped part way
stored --> committed : commit ok, the account is credited
not_stored --> released : release ok
store_jammed --> stored : operator counted, the notes arrived
store_jammed --> not_stored : operator counted, nothing arrived
committed --> [*]
released --> [*]

The Atm’s states gain one: Ready goes to Depositing when notes are taken in; Depositing goes back to Idle on confirm, cancel, or the timeout, or to OutOfService on a store jam.

The step 1 tests run against step 2 with the new constructor argument and the longer balance text. Then:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// The daily limit (FR-8). A reminder: LLD_TEST(name) defines one test,
// LLD_CHECK(condition) records a failure if the condition is false, and
// LLD_CHECK_EQ(actual, expected) records one, showing both values, if
// they differ. They come from the site's test header, lld_test.hpp.
// in<Ready>(machine) is a small helper in this file: true when the
// machine is in that state (std::holds_alternative on its variant).
//
// Step 2's World is step 1's with three changes: it also owns a
// FakeAcceptor, the World's `acceptor`, for deposits; its FakeBank reads
// the World's `clock` to know which day it is; and World(notes, balance,
// limit) takes the card's daily limit as a third argument, 500.00 if it
// is left out. These tests give the card 1000.00, so the balance is never
// what stops a withdrawal: only the limit is. A finished withdrawal ends
// the session, which is why a test signs in again before the next one.
//
// AC-6.1. 300.00 is taken out, leaving 200.00 of the day's 500.00. Then
// 220.00 would make 520.00, so the bank answers limit_exceeded: the
// journal shows that attempt (atm-7-000002, the second id) as holding
// then released, nothing is held, and the session stays in Ready. Then
// 200.00 brings the day to exactly 500.00, which is allowed: the bank
// refuses only a total above the limit.
LLD_TEST(ac_6_1_a_withdrawal_past_the_daily_limit_is_refused_and_the_session_stays) {
World w(50, dollars(1000));
w.sign_in();
LLD_CHECK_EQ(w.atm().withdraw(dollars(300)).cash, dollars(300));
w.sign_in();
LLD_CHECK_EQ(w.atm().withdraw(dollars(220)).text, std::string("That is more than your daily limit allows."));
LLD_CHECK(in<Ready>(w.atm()));
LLD_CHECK(w.stages("atm-7-000002") == (std::vector<Stage>{Stage::holding, Stage::released}));
LLD_CHECK_EQ(w.atm().withdraw(dollars(200)).cash, dollars(200)); // exactly the limit is allowed
LLD_CHECK_EQ(w.bank.taken_today(card), dollars(500));
}
// AC-6.2. A second ATM, `other`, shares the World's bank and clock but
// has its own journal, cassette, and acceptor, like a machine down the
// road. 400.00 taken at atm-7 leaves 100.00 for the day, and the bank,
// which sees both machines, refuses 120.00 at atm-8 and allows 100.00.
LLD_TEST(ac_6_2_the_limit_counts_every_atm) {
World w(50, dollars(1000));
Journal other_journal;
FakeDispenser other_cassette(50);
FakeAcceptor other_acceptor;
AtmConfig other_config = w.config;
other_config.machine_id = "atm-8"; // ids are unique across machines: the bank keys holds by them
Atm other(other_config, w.bank, other_cassette, other_acceptor, other_journal, w.clock);
w.sign_in();
static_cast<void>(w.atm().withdraw(dollars(400)));
static_cast<void>(other.insert_card(card));
static_cast<void>(other.enter_pin(toy::seal("4321", key)));
LLD_CHECK_EQ(other.withdraw(dollars(120)).text, std::string("That is more than your daily limit allows."));
LLD_CHECK_EQ(other.withdraw(dollars(100)).cash, dollars(100));
}
// AC-6.3. A hold counts toward the limit only while it may still become
// cash in someone's hand. First, a dispense that gives nothing (failed):
// the hold is released at once and never counts. Then a jam with no
// notes out (fail_next's notes_out is 0 when left out): the hold stays,
// and its 400.00 counts, because until someone counts the cassette the
// cash may be gone. The operator's resolve(..., false) says no cash left;
// the hold is released and the day is back to nothing taken, and the
// machine is back in service. A third 400.00 then goes through. Had
// either released hold still counted, 400.00 + 400.00 would pass 500.00.
LLD_TEST(ac_6_3_money_that_never_left_does_not_count) {
World w(50, dollars(1000));
w.sign_in();
w.dispenser.fail_next(DispenseStatus::failed);
static_cast<void>(w.atm().withdraw(dollars(400)));
w.sign_in();
w.dispenser.fail_next(DispenseStatus::jammed);
static_cast<void>(w.atm().withdraw(dollars(400)));
LLD_CHECK_EQ(w.bank.taken_today(card), dollars(400)); // a jam counts until it is counted
w.atm().resolve("atm-7-000002", false);
LLD_CHECK_EQ(w.bank.taken_today(card), Money{});
w.sign_in();
LLD_CHECK_EQ(w.atm().withdraw(dollars(400)).cash, dollars(400));
}
// AC-6.4. The World's clock starts at 09:00 UTC on 2 March 2026, and the
// fake bank's day is the calendar day in UTC. 400.00 is taken at 09:00.
// At 23:59 the same day, 200.00 would pass 500.00 and is refused. One
// minute later it is midnight and a new day: the 400.00, made yesterday,
// no longer counts. The balance shows 600.00 (1000.00 less the 400.00)
// and the whole 500.00 for today, and 200.00 is allowed.
LLD_TEST(ac_6_4_the_limit_starts_again_each_day) {
World w(50, dollars(1000));
w.sign_in();
static_cast<void>(w.atm().withdraw(dollars(400)));
// advance takes std::chrono::seconds, so 14 hours 59 minutes is turned
// into seconds first. 09:00 + 14:59 is 23:59.
w.clock.advance(seconds{hours{14} + minutes{59}}); // 23:59 the same day
w.sign_in();
LLD_CHECK_EQ(w.atm().withdraw(dollars(200)).text, std::string("That is more than your daily limit allows."));
static_cast<void>(w.atm().cancel());
w.clock.advance(60s); // midnight
w.sign_in();
LLD_CHECK_EQ(w.atm().check_balance().text, std::string("Available: 600.00. You can take out 500.00 more today."));
LLD_CHECK_EQ(w.atm().withdraw(dollars(200)).cash, dollars(200));
}
// AC-6.5. After 120.00 is taken, the balance screen shows both numbers
// the bank sends: 880.00 available (1000.00 less 120.00), and 380.00
// left of today's 500.00.
LLD_TEST(ac_6_5_the_balance_shows_what_is_left_today) {
World w(50, dollars(1000));
w.sign_in();
static_cast<void>(w.atm().withdraw(dollars(120)));
w.sign_in();
LLD_CHECK_EQ(w.atm().check_balance().text, std::string("Available: 880.00. You can take out 380.00 more today."));
}

ac_6_3 is the case a quick design gets wrong: a hold that was released after a failed dispense must not use up the limit, or a customer whose withdrawal failed twice is locked out for the day without having taken anything.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// Deposits (FR-9). The acceptor's put(count) plays the customer pushing
// notes into the slot; deposit() takes them into escrow and shows the
// total, and confirm() stores and credits them. Notes are 20.00 each, and
// the World's default card has 300.00.
//
// AC-7.1. The whole path with nothing going wrong. Six notes go into
// escrow and the screen shows 120.00. deposit() writes nothing to the
// journal: until confirm, cancel can still give the notes back, so there
// is nothing to recover after a crash. confirm() then writes the four
// stages in order (expecting, storing, stored, committed); the six notes
// are in the store, the balance is 300.00 + 120.00 = 420.00, the card
// comes out, the machine is idle, and the bank session has been ended.
LLD_TEST(ac_7_1_a_deposit_is_stored_then_credited) {
World w;
w.sign_in();
w.acceptor.put(6);
LLD_CHECK_EQ(w.atm().deposit().text, std::string("You put in 120.00. Confirm or cancel."));
LLD_CHECK(in<Depositing>(w.atm()));
LLD_CHECK(w.journal.entries().empty()); // nothing is written until confirm
const Response response = w.atm().confirm();
LLD_CHECK_EQ(response.text, std::string("Deposited 120.00. Take your card."));
LLD_CHECK_EQ(response.card, CardAction::eject);
LLD_CHECK_EQ(w.acceptor.in_store(), 6);
LLD_CHECK_EQ(w.bank.balance(card), dollars(420));
LLD_CHECK(w.stages("atm-7-000001") ==
(std::vector<Stage>{Stage::expecting, Stage::storing, Stage::stored, Stage::committed}));
LLD_CHECK(in<Idle>(w.atm()));
LLD_CHECK_EQ(w.bank.open_sessions(), std::size_t{0});
}
// AC-7.2. Two deposits that are never confirmed. The first, three notes,
// is cancelled, and the three come back. The second, two notes, is left
// for the 30-second timeout. tick() ends a session once 30 seconds or
// more have passed with no input, so at exactly 30 seconds it gives
// those two back too: five notes back in all. Nothing reached the store,
// the journal is still empty, the balance is still 300.00, and no bank
// session is left open.
LLD_TEST(ac_7_2_cancel_or_the_timeout_gives_the_notes_back) {
World w;
w.sign_in();
w.acceptor.put(3);
static_cast<void>(w.atm().deposit());
LLD_CHECK_EQ(w.atm().cancel().text, std::string("Take your notes and your card."));
LLD_CHECK_EQ(w.acceptor.given_back(), 3);
w.sign_in();
w.acceptor.put(2);
static_cast<void>(w.atm().deposit());
w.clock.advance(30s);
LLD_CHECK_EQ(w.atm().tick().text, std::string("No input for a while. Take your notes and your card."));
LLD_CHECK_EQ(w.acceptor.given_back(), 5);
LLD_CHECK_EQ(w.acceptor.in_store(), 0);
LLD_CHECK(w.journal.entries().empty());
LLD_CHECK_EQ(w.bank.balance(card), dollars(300));
LLD_CHECK_EQ(w.bank.open_sessions(), std::size_t{0});
}
// AC-7.3. deposit() with an empty slot accepts nothing, says so, and
// keeps the session in Ready, so confirm() has nothing to confirm and is
// "Not available now." With one note in escrow the machine is in
// Depositing, and every other event waits: a withdrawal, a balance, and a
// second deposit are all refused, and the state does not change.
LLD_TEST(ac_7_3_no_notes_keeps_the_session_and_other_events_wait) {
World w;
w.sign_in();
LLD_CHECK_EQ(w.atm().deposit().text, std::string("No notes were accepted."));
LLD_CHECK(in<Ready>(w.atm()));
LLD_CHECK_EQ(w.atm().confirm().text, std::string("Not available now."));
w.acceptor.put(1);
static_cast<void>(w.atm().deposit());
LLD_CHECK_EQ(w.atm().withdraw(dollars(20)).text, std::string("Not available now."));
LLD_CHECK_EQ(w.atm().check_balance().text, std::string("Not available now."));
LLD_CHECK_EQ(w.atm().deposit().text, std::string("Not available now."));
LLD_CHECK(in<Depositing>(w.atm()));
}
// AC-7.4. The bank does not answer the announcement, expect(). The loop
// runs the same test twice, once for each value in the brace list. With
// applied false, the request was lost on the way. With applied true, the
// bank recorded the expected deposit and only its reply was lost. The
// ATM cannot tell which, so both runs must end the same way: it releases
// the id (the bank answers ok whether or not it had heard of it) and
// gives the five notes back. Nothing is stored, the journal shows
// expecting then released, the bank expects nothing, and the balance is
// still 300.00.
LLD_TEST(ac_7_4_a_bank_that_does_not_answer_gives_the_notes_back) {
for (const bool applied : {false, true}) {
World w;
w.sign_in();
w.acceptor.put(5);
static_cast<void>(w.atm().deposit());
w.bank.fail_next(BankCall::expect, applied);
LLD_CHECK_EQ(w.atm().confirm().text, std::string("The bank is not answering. Take your notes and your card."));
LLD_CHECK_EQ(w.acceptor.given_back(), 5);
LLD_CHECK_EQ(w.acceptor.in_store(), 0);
LLD_CHECK(w.stages("atm-7-000001") == (std::vector<Stage>{Stage::expecting, Stage::released}));
LLD_CHECK_EQ(w.bank.expected(card), Money{});
LLD_CHECK_EQ(w.bank.balance(card), dollars(300));
}
}
// AC-7.5. The store fails before any note moves (StoreStatus::failed),
// so the notes are still in escrow. The ATM gives all five back, writes
// not stored, and releases the expected deposit. Nothing is credited.
LLD_TEST(ac_7_5_notes_the_store_does_not_take_go_back) {
World w;
w.sign_in();
w.acceptor.put(5);
static_cast<void>(w.atm().deposit());
w.acceptor.fail_next(StoreStatus::failed);
LLD_CHECK_EQ(w.atm().confirm().text,
std::string("The machine could not take your notes. Take your notes and your card."));
LLD_CHECK_EQ(w.acceptor.given_back(), 5);
LLD_CHECK(w.stages("atm-7-000001") ==
(std::vector<Stage>{Stage::expecting, Stage::storing, Stage::not_stored, Stage::released}));
LLD_CHECK_EQ(w.bank.balance(card), dollars(300));
}
// AC-7.6. The credit (the commit after stored) gets no answer. The
// screen still says "Deposited", because the notes are in the store and
// the journal now records that the credit is owed. Straight after
// confirm, the balance is 400.00 if the bank applied the credit and
// 300.00 if not, and one entry is open, at stored. The restart shows that
// the journal alone is enough: the new machine's settle sends the commit
// again and returns 0, nothing left open. A repeated commit of an id the
// bank already committed is ok and adds nothing, and the second settle
// has nothing open to send. Either way the balance ends at 400.00: the
// 100.00 is credited exactly once.
LLD_TEST(ac_7_6_a_lost_credit_reply_is_retried_and_credits_once) {
// applied: the bank credits it and the reply is lost. Not applied: the
// request never arrives. The ATM cannot tell the two apart.
for (const bool applied : {false, true}) {
World w;
w.sign_in();
w.acceptor.put(5);
static_cast<void>(w.atm().deposit());
w.bank.fail_next(BankCall::commit, applied);
LLD_CHECK_EQ(w.atm().confirm().text, std::string("Deposited 100.00. Take your card."));
LLD_CHECK_EQ(w.bank.balance(card), applied ? dollars(400) : dollars(300));
LLD_CHECK_EQ(w.journal.open().size(), std::size_t{1});
w.restart(); // even after a restart, the journal says what is owed
LLD_CHECK_EQ(w.atm().settle(), std::size_t{0});
static_cast<void>(w.atm().settle());
LLD_CHECK_EQ(w.bank.balance(card), dollars(400));
LLD_CHECK_EQ(w.bank.expected(card), Money{});
}
}
// AC-7.7. The store jams, run twice: with reached_store true, all five
// notes got into the store before it stopped; with false, none did. The
// ATM cannot see which, so both runs start the same way: it writes store
// jammed, the bank still expects the 100.00, and the machine is out of
// service. A restart reads the same entry from the journal and stays out
// of service. The operator then counts and passes the truth to resolve:
// if the notes reached the store, the deposit is committed and the
// balance is 400.00; if not, it is released and the balance stays 300.00.
// Either way the bank expects nothing more and the machine is idle.
LLD_TEST(ac_7_7_a_store_jam_waits_for_an_operator) {
for (const bool reached_store : {true, false}) {
World w;
w.sign_in();
w.acceptor.put(5);
static_cast<void>(w.atm().deposit());
w.acceptor.fail_next(StoreStatus::jammed, reached_store ? 5 : 0);
static_cast<void>(w.atm().confirm());
LLD_CHECK(in<OutOfService>(w.atm()));
LLD_CHECK_EQ(w.bank.expected(card), dollars(100));
w.restart();
LLD_CHECK(in<OutOfService>(w.atm()));
w.atm().resolve("atm-7-000001", reached_store);
LLD_CHECK(in<Idle>(w.atm()));
LLD_CHECK_EQ(w.bank.balance(card), reached_store ? dollars(400) : dollars(300));
LLD_CHECK_EQ(w.bank.expected(card), Money{});
LLD_CHECK(w.stages("atm-7-000001").back() == (reached_store ? Stage::committed : Stage::released));
}
}
// AC-7.8. A journal left as a crash would leave it, one row per case.
// Case is a small struct written inside the test: the last stage written,
// whether the bank had heard of the deposit, the balance expected after
// settle, and whether only an operator can finish it. Each row:
// expecting, heard release, nothing credited 300.00
// expecting, not heard release of an unknown id (ok) 300.00
// not stored release 300.00
// stored commit: credited 400.00
// storing out of service; settle leaves 1 open 300.00
// For each row the test plays the bank's side by hand (verify opens a
// session; expect announces the deposit if the bank heard), appends the
// journal entries up to the row's last stage, restarts, and settles. For
// the deposit the bank never heard of, it then sends the announcement
// late and checks that the bank refuses it.
LLD_TEST(ac_7_8_after_a_crash_settle_finishes_a_deposit_that_software_can) {
struct Case {
Stage last;
bool bank_heard;
Money balance_after;
bool operator_needed;
};
for (const Case c : {Case{Stage::expecting, true, dollars(300), false},
Case{Stage::expecting, false, dollars(300), false},
Case{Stage::not_stored, true, dollars(300), false},
Case{Stage::stored, true, dollars(400), false},
Case{Stage::storing, true, dollars(300), true}}) {
World w;
// Straight to the bank, not through an ATM: this only opens a session.
const PinReply signed_in = w.bank.verify(card, toy::seal("4321", key));
if (c.bank_heard) {
LLD_CHECK_EQ(w.bank.expect(signed_in.session, "atm-7-000001", dollars(100)), BankStatus::ok);
}
// Each brace list is an Entry, in the order of its fields: id, masked
// card, amount, stage, and time. Every row starts at expecting; all but
// expecting add storing; and stored and not stored add their own stage.
w.journal.append({"atm-7-000001", "****7899", dollars(100), Stage::expecting, start});
if (c.last != Stage::expecting) w.journal.append({"atm-7-000001", "****7899", dollars(100), Stage::storing, start});
if (c.last != Stage::expecting && c.last != Stage::storing) {
w.journal.append({"atm-7-000001", "****7899", dollars(100), c.last, start});
}
w.restart();
LLD_CHECK_EQ(in<OutOfService>(w.atm()), c.operator_needed);
// settle returns how many entries are still open: 1 for the row only an
// operator can finish, 0 for every other.
LLD_CHECK_EQ(w.atm().settle(), std::size_t{c.operator_needed ? 1u : 0u});
LLD_CHECK_EQ(w.bank.balance(card), c.balance_after);
if (!c.bank_heard) {
// An announcement that arrives after the release credits nothing.
LLD_CHECK_EQ(w.bank.expect(signed_in.session, "atm-7-000001", dollars(100)), BankStatus::conflict);
LLD_CHECK_EQ(w.bank.expected(card), Money{});
}
}
}
// AC-7.9. A driver that throws. Broken is a stand-in acceptor written
// inside the test: take_in always accepts 4 notes, store() throws, and
// give_back does nothing. The test builds its own Atm on the World's
// bank, dispenser, journal, and clock, with Broken as the acceptor;
// `broken` is declared before `machine`, so it lives longer than the Atm
// that points to it. confirm catches the exception and treats it as a
// jam, because after a throw nobody knows where the notes are: the one
// open entry is at store jammed, and the machine is out of service.
LLD_TEST(ac_7_9_an_acceptor_that_throws_is_treated_as_a_jam) {
class Broken final : public NoteAcceptor {
public:
[[nodiscard]] int take_in() override { return 4; }
[[nodiscard]] StoreStatus store() override { throw std::runtime_error("driver crashed"); }
void give_back() override {}
};
World w;
Broken broken;
Atm machine(w.config, w.bank, w.dispenser, broken, w.journal, w.clock);
static_cast<void>(machine.insert_card(card));
static_cast<void>(machine.enter_pin(toy::seal("4321", key)));
static_cast<void>(machine.deposit());
static_cast<void>(machine.confirm());
LLD_CHECK(in<OutOfService>(machine));
const std::vector<Entry> open = w.journal.open();
LLD_CHECK_EQ(open.at(0).stage, Stage::store_jammed);
}
// AC-7.10. Ten notes, 200.00, are deposited. None of it counts as taken
// today, and it does not raise the limit either: the balance shows
// 1200.00 available (1000.00 + 200.00) but still 500.00 to take out
// today, not 700.00.
LLD_TEST(ac_7_10_a_deposit_does_not_count_toward_the_limit_or_unlock_more) {
World w(50, dollars(1000));
w.sign_in();
w.acceptor.put(10);
static_cast<void>(w.atm().deposit());
static_cast<void>(w.atm().confirm());
LLD_CHECK_EQ(w.bank.taken_today(card), Money{});
w.sign_in();
LLD_CHECK_EQ(w.atm().check_balance().text, std::string("Available: 1200.00. You can take out 500.00 more today."));
}

The random test now mixes deposits into the run, with store failures and jams, a limit of 3,000.00, and a day passing now and then:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// Random sessions, withdrawals, deposits, failures of every kind, new
// days, restarts, and an operator who counts truthfully. At the end, no
// money is lost or made: the account changed by exactly the cash that
// came out and the notes that reached the store.
//
// How it works. std::mt19937 is the standard library's Mersenne Twister
// random number generator. Seeded with the fixed number 2026, it gives
// the same numbers on every run, so a failure can be run again exactly.
// pick(12) turns its next number into a whole number from 0 to 11. Each
// of the 4,000 steps picks one of 12 actions; 10 and 11 both land on
// default, a settle. After every step two invariants are checked; after
// the loop, everything still open is finished and the money is counted.
// The card has 100,000.00 and a limit of 3,000.00 a day, and the
// cassette 5,000 notes: large, so that a long run does not simply run out
// of money or notes.
LLD_TEST(inv_money_moves_only_with_notes) {
std::mt19937 random(2026);
auto pick = [&](int n) { return static_cast<int>(random() % static_cast<unsigned>(n)); };
const Money limit = dollars(3000);
World w(5000, dollars(100000), limit);
// For each withdrawal or deposit the test made jam: true if its notes
// really moved (all of them), false if none did. The operator in case 6
// reads it, so the operator always counts truthfully.
std::map<TxnId, bool> moved_by_jam; // what the operator will find
for (int step = 0; step < 4000; ++step) {
switch (pick(12)) {
case 0: static_cast<void>(w.atm().cancel()); break;
// Case 1 signs in and then runs case 2's code too: [[fallthrough]] says
// the missing break is on purpose. Case 2 on its own tries a withdrawal
// in whatever state the machine is in, so it may be refused.
case 1: w.sign_in(); [[fallthrough]];
case 2: {
// before: how many ids the journal had given out. If that grows, the
// withdrawal passed the checks and was given an id.
const auto before = w.journal.started();
// 1 to 20 notes: 20.00 to 400.00. Then how it ends, set up in advance:
// 0 the dispense fails, 1 it jams with nothing out, 2 it jams with every
// note out, and 3 to 9 (seven times in ten) it works.
const int notes = 1 + pick(20);
const int how = pick(10);
if (how == 0) w.dispenser.fail_next(DispenseStatus::failed);
if (how == 1) w.dispenser.fail_next(DispenseStatus::jammed, 0);
if (how == 2) w.dispenser.fail_next(DispenseStatus::jammed, notes);
static_cast<void>(w.atm().withdraw(dollars(20 * notes)));
// A new withdrawal started and a jam was set up: remember, under its id
// (the last entry written is this withdrawal's), whether the cash left.
// If the bank refused the hold, the dispenser was never used and this
// is never read, because that entry never waits for an operator.
if (w.journal.started() > before && (how == 1 || how == 2)) {
moved_by_jam[w.journal.entries().back().id] = how == 2;
}
// A failure set up above but not used (the withdrawal was refused before
// dispensing) would otherwise hit a later withdrawal that has no entry in
// moved_by_jam. Setting the next outcome back to dispensed, the normal
// one, clears it.
w.dispenser.fail_next(DispenseStatus::dispensed); // a failure not used is cleared
break;
}
// Case 3 sets up one bank failure: one of the six BankCall kinds, cast
// from 0 to 5 (verify, available, hold, expect, commit, release), and
// half the time applied, which means the bank does the work and only the
// reply is lost. It waits until the next call of that kind.
case 3: w.bank.fail_next(static_cast<BankCall>(pick(6)), pick(2) == 1); break;
case 4:
// Time passes: one time in 30 a whole day (a new day for the limit),
// otherwise 0 to 39 seconds, which may pass the 30-second timeout. Both
// sides of ?: are std::chrono::seconds, so the expression has one type.
// Then tick settles and checks the timeout.
w.clock.advance(pick(30) == 0 ? seconds{hours{24}} : seconds{pick(40)});
static_cast<void>(w.atm().tick());
break;
case 5:
// A power cut with notes in escrow is not modelled: see the page.
// A restart is a power cut and a reboot on the same journal, bank, and
// devices. It is skipped in Depositing because deposit() wrote nothing,
// so the notes in escrow live only in the Depositing state, which the
// restart destroys, and in the fake acceptor, which would keep them. The
// design does not cover that case (Production limitations, on the page),
// so the test does not check a made-up answer for it.
if (!in<Depositing>(w.atm())) w.restart();
break;
// Case 6 is the operator: every open entry that only a person can finish
// is resolved with the truth from moved_by_jam. journal.open() returns a
// copy, so resolve can append to the journal while this loop reads it.
// moved_by_jam.at throws if an id is missing, and the test runner counts
// that as a failure: every operator stage must come from a jam set up here.
case 6:
for (const Entry& entry : w.journal.open()) {
if (needs_operator(entry.stage)) w.atm().resolve(entry.id, moved_by_jam.at(entry.id));
}
break;
case 7: static_cast<void>(w.atm().check_balance()); break;
// Case 8 is a deposit: sign in, put 0 to 7 notes in the slot, and take
// them into escrow (with none, deposit says no notes were accepted). One
// time in 3 it stops there and leaves the notes in escrow for a later
// cancel, timeout, or confirm; otherwise it falls through to confirm.
case 8:
w.sign_in();
w.acceptor.put(pick(8));
static_cast<void>(w.atm().deposit());
if (pick(3) == 0) break; // and sometimes wait: cancel, a timeout, or a restart
[[fallthrough]];
// Case 9 confirms whatever is in escrow, with the same three ways to go
// wrong as a withdrawal: 0 the store fails, 1 it jams with nothing in the
// store, 2 it jams with every note in the store. The escrow count is read
// first so that how == 2 knows how many notes to store.
case 9: {
const auto before = w.journal.started();
const int escrow = w.acceptor.in_escrow();
const int how = pick(10);
if (how == 0) w.acceptor.fail_next(StoreStatus::failed);
if (how == 1) w.acceptor.fail_next(StoreStatus::jammed, 0);
if (how == 2) w.acceptor.fail_next(StoreStatus::jammed, escrow);
static_cast<void>(w.atm().confirm());
// As for a withdrawal: remember whether this deposit's notes reached the
// store.
if (w.journal.started() > before && (how == 1 || how == 2)) {
moved_by_jam[w.journal.entries().back().id] = how == 2;
}
// Clears a store failure that was not used, as for the dispenser above.
w.acceptor.fail_next(StoreStatus::stored);
break;
}
// 10 and 11: settle.
default: static_cast<void>(w.atm().settle()); break;
}
// The bank never holds more than the open withdrawals, and never
// lets a day pass the limit.
// open adds up the amounts of the open withdrawals: those whose first
// stage is holding (a deposit's is expecting). A new Money is 0.00. The
// bank may hold less than that (a hold that never arrived, or a commit or
// release applied but whose reply was lost), but never more: more would
// mean money held for a withdrawal the journal has lost track of.
Money open;
for (const Entry& entry : w.journal.open()) {
if (w.stages(entry.id).front() == Stage::holding) open = open + entry.amount;
}
LLD_CHECK(w.bank.held(card) <= open);
LLD_CHECK(w.bank.taken_today(card) <= limit);
}
// At most one failure of each kind can be waiting, and a settle uses up
// any commit or release failure it meets, so after a few settles none
// is left to stop one. Then an operator finishes the rest.
// The last settle, after the operator, sends again any commit or release
// from resolve that met a waiting bank failure.
for (int i = 0; i < 3; ++i) static_cast<void>(w.atm().settle());
for (const Entry& entry : w.journal.open()) {
if (needs_operator(entry.stage)) w.atm().resolve(entry.id, moved_by_jam.at(entry.id));
}
static_cast<void>(w.atm().settle());
LLD_CHECK(w.journal.open().empty());
LLD_CHECK_EQ(w.bank.held(card), Money{});
LLD_CHECK_EQ(w.bank.expected(card), Money{});
// Nothing is open, held, or expected. Each note is 20.00, that is 2000
// cents, and std::int64_t{2000} makes the multiplication use the 64-bit
// type that Money holds. So the balance must be the start, less 20.00 for
// every note given out, plus 20.00 for every note that reached the store.
const Money out{std::int64_t{2000} * w.dispenser.presented()};
const Money in_store{std::int64_t{2000} * w.acceptor.in_store()};
LLD_CHECK_EQ(w.bank.balance(card), dollars(100000) - out + in_store);
// The run really moved many notes each way, so the balance check above
// was not passed by a run that did almost nothing.
LLD_CHECK(w.dispenser.presented() > 500);
LLD_CHECK(w.acceptor.in_store() > 100);
}
How this code works: The step 2 random run
  1. The same run every time. As in step 1, std::mt19937 random(2026) has a fixed seed, so the 4,000 choices are the same on every run. pick(12) gives a whole number from 0 to 11; 10 and 11 both settle.
  2. The new kinds of step. Time passing is a whole day one time in 30, so the limit starts again now and then. A deposit signs in, puts 0 to 7 notes in the slot, and takes them into escrow; one time in three it stops there, so a later cancel, timeout, or confirm finds notes in escrow, and otherwise it goes on to confirm. A confirm, like a withdrawal, may be set up to fail, to jam with nothing stored, or to jam with every note stored.
  3. The operator knows the truth. moved_by_jam records, for each jam the test set up, whether the notes really moved, and the operator step passes exactly that to resolve.
  4. Only withdrawals count toward the held total. The per-step check adds up the open entries whose first stage is holding; deposits, which start at expecting, hold no money.
  5. No restart in Depositing. Notes in escrow are recorded nowhere but the Depositing state, which a restart destroys. The design does not cover that case, so the test does not check a made-up answer.

After every step it checks that the bank holds no more than the open withdrawals and that nothing taken today passes the limit. At the end, the balance must be the start, less the cash out, plus the notes in the store. It skips a restart while notes are in escrow, a case the design does not cover; see Production limitations.

Checking the tests. 11 mutations of the step 2 code were run the same way: storing before the bank hears of the deposit, counting released holds toward the limit, counting deposits toward it, a limit that never resets, finish not committing stored, store jammed not an operator stage, cancel keeping the notes, a failed store not giving them back, a deposit credited as a debit, the limit never checked, and an exception from the acceptor escaping. Each made at least one test fail.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The same composition root as step 1, with an acceptor, and a bank
// that reads the same clock to know which day it is. The clock is
// declared first, because the bank keeps a pointer to it.
constexpr unsigned pin_key = 0x5a;
ManualClock clock(sys_days{year{2026} / 3 / 2} + 9h); // 2 March 2026, 09:00
FakeBank bank(pin_key, clock);
FakeDispenser dispenser(50);
FakeAcceptor acceptor;
Journal journal;
const std::string card = "4000001234567899";
bank.open_account(card, "4321", dollars(900), dollars(500)); // 900.00, limit 500.00 a day
const AtmConfig config{"atm-7", dollars(20), dollars(400), 30s};
// The Atm lives in a std::unique_ptr this time, so the demo can destroy
// it and build a new one in the same variable to play a restart.
auto machine = std::make_unique<Atm>(config, bank, dispenser, acceptor, journal, clock);
static_cast<void>(machine->settle());
// A small local function (a lambda). [&] lets it use `machine` and
// `card` from here by reference, not as copies, so after the restart
// it signs in to the new Atm.
auto sign_in = [&] {
static_cast<void>(machine->insert_card(card));
static_cast<void>(machine->enter_pin(toy::seal("4321", pin_key)));
};
sign_in();
show("balance", machine->check_balance());
show("withdraw 400.00", machine->withdraw(dollars(400)));
sign_in();
// 400.00 already taken today, plus 200.00, passes 500.00: the bank
// refuses, and the session stays open, so the balance needs no new
// sign-in. The refused try still used an id (atm-7-000002), recorded
// as holding then released, so the deposit below is atm-7-000003.
show("withdraw 200.00", machine->withdraw(dollars(200)));
show("balance", machine->check_balance());
std::cout << "the customer puts 7 notes in the slot:\n";
acceptor.put(7);
show("deposit", machine->deposit());
std::cout << "the bank does not answer the next commit:\n";
// No `true`: the commit fails before the bank does anything, so the
// 140.00 is not credited, and the entry stays at stored.
bank.fail_next(BankCall::commit);
show("confirm", machine->confirm());
std::cout << " journal: " << journal.open().size() << " open, " << journal.open().front().id << " "
<< to_string(journal.open().front().stage) << "\n";
show_bank(bank, card);
std::cout << "the ATM restarts on the same journal:\n";
// reset() destroys the old Atm first; then a new one is built on the
// same journal. Its settle finds the deposit at stored and commits it.
machine.reset();
machine = std::make_unique<Atm>(config, bank, dispenser, acceptor, journal, clock);
std::cout << " settle: " << machine->settle() << " still open\n";
show_bank(bank, card);
std::cout << "the next morning:\n";
clock.advance(hours{24}); // a new day at the bank: the limit starts again
sign_in();
show("withdraw 200.00", machine->withdraw(dollars(200)));
sign_in();
acceptor.put(3);
show("deposit", machine->deposit());
show("cancel", machine->cancel()); // the 3 notes in escrow come back
show_bank(bank, card);
std::cout << "notes: " << acceptor.in_store() << " in the store, " << acceptor.given_back() << " given back\n";
Expected output
balance: Available: 900.00. You can take out 500.00 more today.
withdraw 400.00: Take your card, then your cash. [card out] [cash 400.00]
withdraw 200.00: That is more than your daily limit allows.
balance: Available: 500.00. You can take out 100.00 more today.
the customer puts 7 notes in the slot:
deposit: You put in 140.00. Confirm or cancel.
the bank does not answer the next commit:
confirm: Deposited 140.00. Take your card. [card out]
journal: 1 open, atm-7-000003 stored
bank: balance 500.00, taken today 400.00
the ATM restarts on the same journal:
settle: 0 still open
bank: balance 640.00, taken today 400.00
the next morning:
withdraw 200.00: Take your card, then your cash. [card out] [cash 200.00]
deposit: You put in 60.00. Confirm or cancel.
cancel: Take your notes and your card. [card out]
bank: balance 440.00, taken today 200.00
notes: 7 in the store, 3 given back
  • 400.00 uses most of the day’s 500.00, so a second 200.00 is refused, and the balance says 100.00 is left today.
  • The deposit of seven notes is stored, but the bank does not answer the credit (in the demo it never applied it). The journal holds one deposit at stored, and the balance has not moved yet.
  • The restart settles it: the credit is sent again, and the balance rises by 140.00, once. The deposit did not raise the limit.
  • The next morning the limit starts again, and 200.00 goes through. A second deposit is cancelled, and its three notes come back.

A plan for 45 minutes, using the time boxes from The design workflow:

Time What to do What to say
About 5 min Ask what the bank offers, who checks the PIN, how the dispenser fails, what happens after a jam, and whether the machine can lose power. “When the dispenser jams, does anyone know how many notes came out?”
5 min Sketch the states, Bank and CashDispenser as interfaces, the Atm, and the journal. Say who owns what. “The journal outlives the controller: a restart is a new controller on the same journal.”
10–15 min Write the states as a variant, then withdraw: hold, dispense, commit, each preceded by a journal entry. State INV-1 and INV-2. “Everything that can fail goes before the dispense. What comes after it must be safe to repeat.”
10 min Walk the stage table: a crash at each stage, and what settle does. Show the lost commit, and the jam that waits for an operator. “Some failures software cannot finish. Those become a state that waits for a person, not a guess.”
About 5 min Take a change: a daily limit, or deposits. “The limit spans machines, so the bank keeps it. A deposit is a withdrawal in reverse.”

What is usually expected at each level

Level Usually expected
Junior States for the session (idle, card in, PIN entered); a bank interface; checks on the amount; a dispenser that can fail; returning the card; a few tests with fakes.
Mid-level All of the above, plus: states that hold their own data; hold then commit or release; a bank that may not answer; a timeout from an injected clock; the PIN checked and counted by the bank; money in integer cents.
Senior All of the above, plus: a journal written before each step and read on restart; idempotent requests keyed by an id that survives restarts; a jam as a state that waits for an operator; the PIN as a sealed block; the daily limit in the bank; deposits through an escrow.

These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.

  • The journal is in memory. A real journal is a file, flushed to storage before each append returns, and read back on start-up. Its entries would also need a checksum, so that a half-written last entry after a power cut is detected and ignored rather than misread.
  • A jam is all or nothing. The operator says “the cash left” or “it did not”. A real count can find that 40.00 of 100.00 left. See the Exercise.
  • Notes in escrow at a power cut are not modelled. A machine that restarts with a customer’s notes in escrow has no journal entry for them, because nothing was written before confirm. A crash after confirm records expecting but before store is no better: settle releases what the bank expected (AC-7.8), and nothing deals with the notes still in escrow. The fake acceptor would keep them for the next customer. A real machine returns or retains escrowed notes on start-up and records it; the step 2 random test skips this case rather than pretend.
  • One denomination. A real dispenser chooses notes from several cassettes, and can run out of one.
  • Ids assume order. The six-digit number sorts correctly up to 999,999 withdrawals per machine, and ids are unique only if machine ids are.
  • The bank keeps holds and sessions for ever. A real bank lets an unconfirmed hold expire, and reconciles against the machine’s journal later. It also expires a session that a power cut left open, because the restarted machine has no session to end.
  • The PIN sealing is a toy. It hides digits from a casual reader in a demo, and nothing more.
  • Synchronous devices on one thread. Each device call blocks until it returns. A real controller needs a deadline on every device and bank call, and a dispenser that never answers is a jam.
  • The journal never shrinks. A real one is archived once its entries are final and reconciled.
Requirement Design element Code Tests Status
FR-1 session AwaitingPin, Ready, enter_pin, Bank::verify step 1 atm.*, bank.hpp ac_1_1_… to ac_1_4_… Tested
FR-2 balance check_balance, Bank::available step 1 atm.cpp ac_2_1_…, ac_2_2_… Tested
FR-3 withdrawal withdraw, Response, AtmConfig step 1 atm.* ac_3_1_… to ac_3_3_…, ac_3_10_… Tested
FR-4 no money without cash hold, dispense, commit; finish; the journal step 1 atm.cpp, journal.* ac_3_4_… to ac_3_9_…, random test Tested
FR-5 recovery settle, resolve, needs_operator, resting_state step 1 atm.cpp, journal.hpp ac_4_1_… to ac_4_5_…, random test Tested
FR-6 sessions end cancel, tick, end_session step 1 atm.cpp ac_1_5_…, ac_1_6_… Tested
FR-7 out of service OutOfService, resting_state step 1 atm.cpp ac_3_8_…, ac_3_10_…, ac_4_2_… Tested
NFR-1 the PIN stays sealed PinBlock, masked step 1 pin.hpp, journal.cpp ac_1_8_… Tested
NFR-2 requests safe to repeat the Bank contract, TxnId, next_id step 1 bank.hpp, fake_bank.cpp ac_3_7_…, ac_4_3_…, ac_4_6_… Tested
NFR-3 testable without hardware Bank, CashDispenser, Clock, and fakes step 1 headers every test Tested
NFR-4 not thread-safe documented on Atm step 1 atm.hpp none: a statement, not a behaviour Stated
NFR-5 exact money Money in cents step 1 money.hpp ac_3_2_… and every balance check Tested
FR-8 daily limit limit_exceeded, left_today, the fake bank’s day count step 2 bank.hpp, fake_bank.cpp ac_6_1_… to ac_6_5_…, ac_7_10_…, step 2 random test Tested
FR-9 deposit NoteAcceptor, Depositing, confirm, deposit stages step 2 note_acceptor.hpp, atm.cpp ac_7_1_… to ac_7_9_…, step 2 random test Tested

Exercise: Count what the jam let out

The engineers say that “all or nothing” is not what they find. After a jam, the count usually shows that some notes left and some did not. Change the design so that the operator enters the amount that moved, and the customer is charged (or, for a deposit, credited) exactly that. Start from step 2.

  1. Which part of the bank’s contract has to change? What should a repeat of the changed request do?
  2. Where does the counted amount live after resolve, so that a restart before the bank answers still commits the right amount?
  3. Which counts must resolve refuse?
  4. Write it, and a test for each answer.
  5. Run the step 2 random test with partial jams. Which check breaks first, and is it the code or the check that is wrong?
Show the explained answer
  1. commit takes the amount. commit(id, amount) commits at most the amount held (or expected, for a deposit) and releases the rest in the same step, so that no second request is needed. A repeat with the same amount is ok; a repeat with a different amount is a conflict, because it cannot be a resend of the same request. An amount of zero is not a commit; it is a release.

    IllustrativeA fragment for explanation; not compiled on its own.

    // in FakeBank::commit(const TxnId& id, Money amount)
    // `found` is the hold for this id, looked up as in step 2's commit.
    if (found == holds_.end()) {
    status = BankStatus::unknown;
    // `Hold& hold = ...;` before the condition declares a name that the
    // later else-if branches can use too.
    } else if (Hold& hold = found->second; hold.state == HoldState::released) {
    status = BankStatus::conflict;
    } else if (hold.state == HoldState::committed) {
    if (amount != hold.amount) status = BankStatus::conflict; // not a resend
    } else {
    // zero never reaches here: resolve sends it to release
    if (amount <= Money{} || amount > hold.amount) throw std::invalid_argument("commit more than zero, at most the hold");
    hold.amount = amount; // the rest is released with it
    // A reference to the balance itself, so the line below changes it:
    // up for a deposit, down for a withdrawal.
    Money& funds = accounts_.at(hold.card).balance;
    funds = hold.deposit ? funds + hold.amount : funds - hold.amount;
    hold.state = HoldState::committed;
    }
  2. In the journal. resolve records the dispensed (or stored) entry with the counted amount, and finish commits last.amount. Then a crash after resolve and before the bank answers leaves the counted amount in the last entry, and settle commits that. Keeping the count only in a variable, or passing it straight to commit, would lose it with the power.

  3. Anything that cannot be a count. A negative amount, more than the withdrawal asked for, or an amount that is not whole notes. Each throws std::invalid_argument and changes nothing, so the operator can try again. Zero is allowed: it is “nothing moved”, and releases.

  4. One way, in atm.cpp:

    IllustrativeA fragment for explanation; not compiled on its own.

    void Atm::resolve(const TxnId& id, Money moved) {
    // `Entry entry`, a copy, not `const Entry&`: its amount is changed below.
    for (Entry entry : journal_->open()) {
    if (entry.id != id || !needs_operator(entry.stage)) continue;
    // Checked before anything is recorded, so a refused count changes nothing.
    if (moved < Money{} || moved > entry.amount || moved.cents % config_.note.cents != 0) {
    throw std::invalid_argument("the count must be whole notes, at most the amount asked for");
    }
    const bool deposit = entry.stage == Stage::storing || entry.stage == Stage::store_jammed;
    const Stage moved_stage = deposit ? Stage::stored : Stage::dispensed;
    const Stage not_moved = deposit ? Stage::not_stored : Stage::not_dispensed;
    // Zero moved means "nothing moved": record the not-moved stage,
    // and finish releases. Otherwise record the moved stage with the
    // counted amount, and finish commits that amount.
    const bool any = moved > Money{};
    if (any) entry.amount = moved; // from here on, the journal says what moved
    static_cast<void>(finish(record(entry, any ? moved_stage : not_moved)));
    if (std::holds_alternative<OutOfService>(state_)) state_ = resting_state();
    return;
    }
    throw std::invalid_argument("no withdrawal waits for an operator under " + id);
    }

    and in finish, bank_->commit(last.id, last.amount). The loop variable is a copy now, because the entry is changed before it is recorded. The tests:

    • A jam with 40.00 of 100.00 out charges 40.00, holds nothing, and counts 40.00 toward the day’s limit.
    • A store jam with 60.00 of 100.00 in the store credits 60.00.
    • 120.00, 10.00, and −20.00 are refused, the journal is unchanged, and the machine stays out of service.
    • With the commit’s reply lost after resolve, a restart and settle commit 40.00; a second commit of 40.00 is ok, and of 100.00 a conflict.
  5. The check breaks, not the code. The per-step check “the bank holds no more than the open withdrawals” summed the amounts of the open entries. After a partial resolve whose commit is not yet through, the open entry says 40.00, but the bank still holds 100.00 until the commit arrives. The bank is right: the hold is released only by the commit. The check was reading the wrong number. The fix is to sum the amount from the first entry of each open withdrawal, the amount held. The other way is to keep the counted amount in a field of its own, next to the amount asked for, so that an entry says both. That costs a field and makes each entry clearer; either is defensible, and the choice should be written down.

This answer was checked in a scratch copy of step 2; it is not part of the example in the repository. With these changes, the four tests above passed along with the other step 2 tests (with resolve given amounts instead of booleans, and the random test using partial jams) under GCC, Clang, and AddressSanitizer with UndefinedBehaviorSanitizer.

  • Make the session’s states types, each holding only what exists in it. A bank session that exists only in Ready cannot leak into Idle.
  • Hold, dispense, commit. Put everything that can fail before the step that cannot be undone, and make everything after it safe to repeat.
  • Write the stage before the step. After a power cut, the last entry of each withdrawal names the one step that may have happened, and so the one thing to do.
  • Some facts are about paper, not data. When software cannot know how much moved, make it a state that waits for a person.
  • Key every request to the bank by an id that survives restarts, and let the bank make repeats harmless.
  • Keep secrets out of code that does not need them. The ATM forwards a sealed PIN and never reads one, and the bank counts wrong tries.
  • A rule that spans machines, like a daily limit, lives with the party that sees every machine. A deposit is a withdrawal in reverse, and the same journal and stages carry it.