Skip to content

Checkpoint: An All-or-Nothing Batch

The Course
•
40 min study

This checkpoint is the engine's core in miniature. You combine today's three ideas, staging, per-event validation and explicit results, with Day 2's owned rules. The result is a function that either applies a whole batch or leaves the inventory exactly as it was, and that says precisely which event failed and why. A late rejection must discard every earlier change in the same batch, including items the batch created. Keep rule callbacks observational: the engine can roll back its own inventory, but not output, files or anything else a rule might touch.

Predict and run

Predict before running C++
#include <iostream>
#include <vector>

int main() {
    std::vector<int> deltas{5,-99};
    int live = 10, staged = live;
    bool valid = true;
    for (int delta : deltas) { staged += delta; if (staged < 0) { valid = false; break; } }
    if (valid) { live = staged; }
    std::cout << live << "\n";
    return 0;
}
Check your prediction
Text
10

The +5 was applied to staged, then -99 drove it to -84, so the loop stopped and live was never assigned. Now compare an end-only check. For the sequence -15, +10 from 10, the final value is 5, which is valid, while the intermediate value -5 is not. A check of only the final total would accept it. The loop above checks after every step, so it rejects it, which is the engine's specified behavior.

What you will use

  • Typed events in a variant. Create{id, quantity} and Adjust{id, delta}, applied by a visitor that returns an Error.
  • Owned runtime rules. std::vector<std::unique_ptr<Rule>>, each rule inspecting the staged inventory after every event.
  • A staged copy and one swap. All work happens on the copy; swap publishes it.
  • A preflight check. An oversized batch is rejected before processing, with no index.
  • BatchResult. An Error and a std::optional<std::size_t> index.

Plan before you type

  1. Write the Apply visitor over a staged std::map<int,int>&. A Create rejects a duplicate ID; an Adjust rejects a missing ID or a result outside 0..1000.
  2. Write Rule with virtual bool accepts(const std::map<int,int>& proposed) const = 0; and a TotalLimit that sums the proposed quantities.
  3. With using Inventory = std::map<int,int>;, write Engine::apply(std::span<const Event> events): preflight the size, copy state_, then for each index visit the event and check every rule, returning {error, index} on the first failure.
  4. After the loop, swap and return success.
  5. Export the inventory as text after each batch, so each line shows the whole state, not just the result.

Exporting the whole state after every batch is the part people skip. It is also the only check that catches a batch that reports failure correctly but leaves changes behind.

Prove it can fail

Change Inventory staged = state_; to Inventory& staged = state_;, so the batch edits live state directly. This is the first mutation in the project's manifest. The first five result lines stay identical. The exported state does not: after batch 2 a stray 3:2 appears, after batch 3 item 1 holds 18, and by batch 6 the leaked changes push the total over the limit so a valid batch is rejected. Then restore the copy and instead delete the state_.swap(staged); line: batch 1 reports ok but the inventory stays empty, and the later batches that touch an item fail with missing.

Mistakes worth checking for

  • A failed batch leaves a created item behind. The Create handler inserted into state_ instead of the staged map, or the visitor was constructed with the wrong reference.
  • The index is always 0. The loop returns a constant, or uses a range-based for and loses track of the position. Loop over an index, or count alongside.
  • The rule check runs once after the loop. The compensating batch Adjust{1,8}, Adjust{2,-5} is then accepted. Rules belong inside the loop, after each event.
  • The equality case is rejected. TotalLimit used < instead of <=, so a total of exactly 20 fails. That is the project's "exclude policy equality" mutation, and only a test at the boundary catches it.
  • The oversized batch reports index 4. Preflight checks run before the loop and return std::nullopt.

Practice

Exercise

Your turn

Build the mini engine with TotalLimit(20) installed and a maximum batch size of 4, starting empty. Apply six batches and print each result and the full inventory after it:

  1. Create{1,10}, Create{2,5}
  2. Create{3,2}, Adjust{2,-9}
  3. Adjust{1,8}, Adjust{2,-5}
  4. five events of Adjust{1,0}
  5. an empty batch
  6. Adjust{1,5}, Create{3,0}
Shell
batch 1: ok | 1:10 2:5
batch 2: invalid at 1 | 1:10 2:5
batch 3: rule_rejected at 0 | 1:10 2:5
batch 4: batch_too_large | 1:10 2:5
batch 5: ok | 1:10 2:5
batch 6: ok | 1:15 2:5 3:0
Your workspace C++
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <variant>
#include <vector>

struct Create { int id; int quantity; };
struct Adjust { int id; int delta; };
using Event = std::variant<Create, Adjust>;
enum class Error { none, invalid, duplicate, missing, rule_rejected, batch_too_large };
struct BatchResult { Error error; std::optional<std::size_t> index; };

int main() {
    // Write Apply, Rule, TotalLimit and Engine, then run the six batches.
    return 0;
}
Hint 1: the idea

Only one line in apply writes to state_, and it is the last one. Every return above it leaves state_ untouched by construction.

Hint 2: a first step

Start apply with if (events.size() > 4) { return {Error::batch_too_large, std::nullopt}; } and Inventory staged = state_;, then loop for (std::size_t index = 0; index < events.size(); ++index).

Show one solution
Run the solution C++
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <utility>
#include <variant>
#include <vector>

struct Create { int id; int quantity; };
struct Adjust { int id; int delta; };
using Event = std::variant<Create, Adjust>;
enum class Error { none, invalid, duplicate, missing, rule_rejected, batch_too_large };
struct BatchResult { Error error; std::optional<std::size_t> index; };
using Inventory = std::map<int,int>;

struct Apply {
    Inventory& staged;
    Error operator()(const Create& event) const {
        if (event.quantity < 0 || event.quantity > 1000) { return Error::invalid; }
        return staged.emplace(event.id, event.quantity).second ? Error::none : Error::duplicate;
    }
    Error operator()(const Adjust& event) const {
        if (event.delta < -1000 || event.delta > 1000) { return Error::invalid; }
        auto found = staged.find(event.id);
        if (found == staged.end()) { return Error::missing; }
        const int next = found->second + event.delta;
        if (next < 0 || next > 1000) { return Error::invalid; }
        found->second = next;
        return Error::none;
    }
};

class Rule {
public:
    virtual ~Rule() = default;
    virtual bool accepts(const Inventory& proposed) const = 0;
};

class TotalLimit final : public Rule {
public:
    explicit TotalLimit(long maximum) : maximum_(maximum) {}
    bool accepts(const Inventory& proposed) const override {
        long total = 0;
        for (const auto& entry : proposed) { total += entry.second; }
        return total <= maximum_;
    }
private:
    long maximum_;
};

class Engine {
public:
    void add_rule(std::unique_ptr<Rule> rule) { rules_.push_back(std::move(rule)); }
    BatchResult apply(std::span<const Event> events) {
        if (events.size() > 4) { return {Error::batch_too_large, std::nullopt}; }
        Inventory staged = state_;
        for (std::size_t index = 0; index < events.size(); ++index) {
            const Error error = std::visit(Apply{staged}, events[index]);
            if (error != Error::none) { return {error, index}; }
            for (const auto& rule : rules_) {
                if (!rule->accepts(staged)) { return {Error::rule_rejected, index}; }
            }
        }
        state_.swap(staged);
        return {Error::none, std::nullopt};
    }
    std::string export_text() const {
        std::string text;
        for (const auto& [id, quantity] : state_) {
            text += (text.empty() ? "" : " ") + std::to_string(id) + ":" + std::to_string(quantity);
        }
        return text;
    }
private:
    Inventory state_;
    std::vector<std::unique_ptr<Rule>> rules_;
};

const char* name(Error error) {
    switch (error) {
    case Error::none: return "ok";
    case Error::invalid: return "invalid";
    case Error::duplicate: return "duplicate";
    case Error::missing: return "missing";
    case Error::rule_rejected: return "rule_rejected";
    case Error::batch_too_large: return "batch_too_large";
    }
    return "unknown";
}

int main() {
    Engine engine;
    engine.add_rule(std::make_unique<TotalLimit>(20));
    const std::vector<std::vector<Event>> batches{
        {Create{1,10}, Create{2,5}},
        {Create{3,2}, Adjust{2,-9}},
        {Adjust{1,8}, Adjust{2,-5}},
        std::vector<Event>(5, Adjust{1,0}),
        {},
        {Adjust{1,5}, Create{3,0}}};
    for (std::size_t i = 0; i < batches.size(); ++i) {
        const BatchResult result = engine.apply(batches[i]);
        std::cout << "batch " << i + 1 << ": " << name(result.error);
        if (result.index) { std::cout << " at " << *result.index; }
        std::cout << " | " << engine.export_text() << "\n";
    }
    return 0;
}
Text
batch 1: ok | 1:10 2:5
batch 2: invalid at 1 | 1:10 2:5
batch 3: rule_rejected at 0 | 1:10 2:5
batch 4: batch_too_large | 1:10 2:5
batch 5: ok | 1:10 2:5
batch 6: ok | 1:15 2:5 3:0

Batch 2 created item 3 in the staged copy before failing, and the export shows no trace of it. Batch 3 failed at its first event, because the total reached 23 before the compensating -5 could run. Batch 6 lands on a total of exactly 20, the boundary that <= must accept. apply takes a std::span<const Event>, and a const std::vector<Event> converts to it implicitly, so the caller's batches are borrowed, never copied. Day 5 looks closely at that kind of borrowing.

Inspect the engine transaction tests

The project's real engine follows the same shape, with three event kinds, names, an item limit and a batch limit of 256. Run its test suite:

Engine transaction checks C++
#include "engine.h" #include <cassert> #include <iostream> #include <type_traits> static BatchResult apply(Engine& engine, std::initializer_list<Event> events) { return engine.apply(std::span<const Event>(events.begin(), events.size())); } struct CountingRule final : Rule { explicit CountingRule(int& live) : live_(live) { ++live_; } ~CountingRule() override { --live_; } bool accepts(const Inventory&, const Event&) const override { return true; } int& live_; }; int main() { static_assert(!std::is_copy_constructible_v<Engine>); static_assert(std::is_move_constructible_v<Engine>); static_assert(std::has_virtual_destructor_v<Rule>); int live = 0; { Engine owner; auto rule = std::make_unique<CountingRule>(live); assert(owner.add_rule(std::move(rule)) && !rule && live == 1); assert(!owner.add_rule(nullptr)); Engine moved = std::move(owner); assert(live == 1); assert(apply(moved, {Create{1,"Owned",1}}).error == Error::none); } assert(live == 0); Engine engine; assert(engine.add_rule(std::make_unique<TotalLimit>(1500))); auto result = apply(engine, {Create{2,"Bolts",10}, Adjust{2,-3}}); assert(result.error == Error::none && !result.index); const std::string original = export_inventory(engine.snapshot()); assert(original == "2|7|Bolts\n"); result = apply(engine, {Create{1,"Nuts",5}, Adjust{2,-99}}); assert(result.error == Error::invalid && result.index == 1); assert(export_inventory(engine.snapshot()) == original); result = apply(engine, {Create{2,"Replace",20}}); assert(result.error == Error::duplicate && result.index == 0); assert(export_inventory(engine.snapshot()) == original); assert(apply(engine, {Adjust{99,1}}).error == Error::missing); assert(apply(engine, {Rename{99,"Missing"}}).error == Error::missing); assert(apply(engine, {Create{0,"Bad",1}}).error == Error::invalid); assert(apply(engine, {Create{3,"",1}}).error == Error::invalid); assert(apply(engine, {Create{3,"Bad",1001}}).error == Error::invalid); assert(apply(engine, {Adjust{2,1001}}).error == Error::invalid); assert(apply(engine, {Rename{2," Bad"}}).error == Error::invalid); assert(export_inventory(engine.snapshot()) == original); assert(apply(engine, {Create{1,"Nuts",5}, Rename{2,"Steel bolts"}}).error == Error::none); assert(export_inventory(engine.snapshot()) == "1|5|Nuts\n2|7|Steel bolts\n"); auto copy = engine.snapshot(); copy.find(1)->second.quantity = 999; assert(engine.snapshot().find(1)->second.quantity == 5); const std::string before_rule = export_inventory(engine.snapshot()); result = apply(engine, {Create{3,"Large",1000}, Create{4,"Too much",500}}); assert(result.error == Error::rule_rejected && result.index == 1); assert(export_inventory(engine.snapshot()) == before_rule); assert(apply(engine, {}).error == Error::none); std::vector<Event> large(257, Adjust{2,0}); result = engine.apply(large); assert(result.error == Error::batch_too_large && !result.index); assert(export_inventory(engine.snapshot()) == before_rule); const std::vector<std::string> bad{"", "create|1|2", "create|0|1|Bad", "adjust|1|+1", "adjust|1|-", "rename|1| Bad", "rename|1|Bad|extra", "unknown|1|x", "create|1|99999999999999999999999|Huge", "create|1|1|" + std::string(41,'x')}; for (const auto& line : bad) { assert(std::holds_alternative<ParseError>(parse_event(line))); } const std::vector<Event> events{Create{7,"Keep title",0}, Adjust{7,-3}, Rename{7,"Renamed"}}; for (const Event& event : events) { auto canonical = export_event(event); ParseResult parsed = parse_event(canonical); assert(std::holds_alternative<Event>(parsed)); assert(export_event(std::get<Event>(parsed)) == canonical); } assert(export_event(events[0]) == "create|7|0|Keep title"); assert(export_event(events[1]) == "adjust|7|-3"); assert(export_event(events[2]) == "rename|7|Renamed"); auto leading = parse_event("create|0007|0000|Owned"); assert(std::holds_alternative<Event>(leading)); assert(export_event(std::get<Event>(leading)) == "create|7|0|Owned"); ParseResult owned = parse_event(std::string("rename|7|Temporary")); assert(export_event(std::get<Event>(owned)) == "rename|7|Temporary"); assert(count_events(events, [](const Event& e) { return std::holds_alternative<Adjust>(e); }) == 1); assert(count_events(events, [](const Event&) { return false; }) == 0); assert(count_events(std::span<const Event>{}, [](const Event&) { return true; }) == 0); Engine reference_checked; assert(apply(reference_checked,{Create{1,"Seeded",100}}).error == Error::none); int reference_quantity = 100; unsigned long seed = 12345; for (int iteration = 0; iteration < 500; ++iteration) { std::vector<Event> batch; int candidate = reference_quantity; bool valid = true; for (int j = 0; j < 3; ++j) { seed = (seed * 1103515245UL + 12345UL) & 0x7fffffffUL; int delta = (int)(seed % 41) - 20; batch.push_back(Adjust{1,delta}); if (valid) { candidate += delta; if (candidate < 0 || candidate > 1000) { valid = false; } } } result = reference_checked.apply(batch); assert((result.error == Error::none) == valid); if (valid) { reference_quantity = candidate; } assert(reference_checked.snapshot().find(1)->second.quantity == reference_quantity); } Engine full; for (int id = 1; id <= 100; ++id) { assert(apply(full,{Create{id,"Item",1000}}).error == Error::none); } assert(apply(full,{Create{101,"Extra",1}}).error == Error::full); assert(full.snapshot().size() == 100 && total_quantity(full.snapshot()) == 100000L); Engine limit; limit.add_rule(std::make_unique<TotalLimit>(10)); assert(apply(limit,{Create{1,"Max",10}}).error == Error::none); assert(apply(limit,{Adjust{1,1},Adjust{1,-1}}).error == Error::rule_rejected); // Per-event policy. assert(total_quantity(limit.snapshot()) == 10); std::cout << "Engine checks passed\n"; } #include "engine.h" #include <sstream> #include <utility> static bool valid_name(const std::string& name) { if (name.empty() || name.size() > 40 || name.front() == ' ' || name.back() == ' ') { return false; } for (unsigned char ch : name) { if (ch < 32 || ch > 126 || ch == '|') { return false; } } return true; } static bool valid_id(int id) { return id >= 1 && id <= 9999; } struct ApplyVisitor { Inventory& state; Error operator()(const Create& event) const { if (!valid_id(event.id) || !valid_name(event.name) || event.quantity < 0 || event.quantity > 1000) { return Error::invalid; } if (state.find(event.id) != state.end()) { return Error::duplicate; } if (state.size() >= 100) { return Error::full; } state.emplace(event.id, Item{event.name, event.quantity}); return Error::none; } Error operator()(const Adjust& event) const { if (!valid_id(event.id) || event.delta < -1000 || event.delta > 1000) { return Error::invalid; } auto found = state.find(event.id); if (found == state.end()) { return Error::missing; } const int next = found->second.quantity + event.delta; // [-1000,2000], no int overflow. if (next < 0 || next > 1000) { return Error::invalid; } found->second.quantity = next; return Error::none; } Error operator()(const Rename& event) const { if (!valid_id(event.id) || !valid_name(event.name)) { return Error::invalid; } auto found = state.find(event.id); if (found == state.end()) { return Error::missing; } found->second.name = event.name; return Error::none; } }; long total_quantity(const Inventory& inventory) { long total = 0; for (const auto& entry : inventory) { total += entry.second.quantity; } return total; } bool TotalLimit::accepts(const Inventory& proposed, const Event& event) const { (void)event; return total_quantity(proposed) <= maximum_; } bool Engine::add_rule(std::unique_ptr<Rule> rule) { if (!rule) { return false; } rules_.push_back(std::move(rule)); return true; } BatchResult Engine::apply(std::span<const Event> events) { if (events.size() > 256) { return {Error::batch_too_large, std::nullopt}; } Inventory staged = state_; for (std::size_t index = 0; index < events.size(); ++index) { Error error = std::visit(ApplyVisitor{staged}, events[index]); if (error != Error::none) { return {error, index}; } for (const auto& rule : rules_) { if (!rule->accepts(staged, events[index])) { return {Error::rule_rejected, index}; } } } state_.swap(staged); return {Error::none, std::nullopt}; } static std::optional<int> number(std::string_view text, bool signed_value) { if (text.empty()) { return std::nullopt; } std::size_t start = signed_value && text.front() == '-' ? 1 : 0; if (start == text.size()) { return std::nullopt; } for (std::size_t i = start; i < text.size(); ++i) { if (text[i] < '0' || text[i] > '9') { return std::nullopt; } } std::istringstream input{std::string(text)}; int value = 0; if (!(input >> value)) { return std::nullopt; } return value; } ParseResult parse_event(std::string_view line) { std::vector<std::string_view> fields; std::size_t start = 0; for (;;) { const auto end = line.find('|', start); fields.push_back(line.substr(start, end == std::string_view::npos ? end : end - start)); if (end == std::string_view::npos) { break; } start = end + 1; if (fields.size() >= 4) { return ParseError{"Too many fields"}; } } if (fields.size() < 3) { return ParseError{"Missing fields"}; } auto id = number(fields[1], false); if (!id || !valid_id(*id)) { return ParseError{"Invalid id"}; } if (fields[0] == "create" && fields.size() == 4) { auto quantity = number(fields[2], false); std::string name(fields[3]); if (!quantity || *quantity > 1000 || !valid_name(name)) { return ParseError{"Invalid create"}; } return Event{Create{*id, std::move(name), *quantity}}; } if (fields[0] == "adjust" && fields.size() == 3) { auto delta = number(fields[2], true); if (!delta || *delta < -1000 || *delta > 1000) { return ParseError{"Invalid adjustment"}; } return Event{Adjust{*id, *delta}}; } if (fields[0] == "rename" && fields.size() == 3) { std::string name(fields[2]); if (!valid_name(name)) { return ParseError{"Invalid name"}; } return Event{Rename{*id, std::move(name)}}; } return ParseError{"Unknown event or field count"}; } struct ExportVisitor { std::string operator()(const Create& e) const { return "create|" + std::to_string(e.id) + "|" + std::to_string(e.quantity) + "|" + e.name; } std::string operator()(const Adjust& e) const { return "adjust|" + std::to_string(e.id) + "|" + std::to_string(e.delta); } std::string operator()(const Rename& e) const { return "rename|" + std::to_string(e.id) + "|" + e.name; } }; std::string export_event(const Event& event) { return std::visit(ExportVisitor{}, event); } std::string export_inventory(const Inventory& inventory) { std::ostringstream output; for (const auto& entry : inventory) { output << entry.first << '|' << entry.second.quantity << '|' << entry.second.name << '\n'; } return output.str(); } #ifndef EVENT_ENGINE_H #define EVENT_ENGINE_H #include <concepts> #include <cstddef> #include <functional> #include <map> #include <memory> #include <optional> #include <span> #include <string> #include <string_view> #include <variant> #include <vector> struct Create { int id; std::string name; int quantity; }; struct Adjust { int id; int delta; }; struct Rename { int id; std::string name; }; using Event = std::variant<Create, Adjust, Rename>; struct Item { std::string name; int quantity; }; using Inventory = std::map<int, Item>; enum class Error { none, invalid, duplicate, missing, full, rule_rejected, batch_too_large }; struct BatchResult { Error error; std::optional<std::size_t> index; }; struct ParseError { std::string message; }; using ParseResult = std::variant<Event, ParseError>; ParseResult parse_event(std::string_view line); // Borrows input during call; returns owned strings. std::string export_event(const Event& event); // Canonical text for a valid event, no newline. std::string export_inventory(const Inventory& inventory); // ID order, newline per item. long total_quantity(const Inventory& inventory); class Rule { public: virtual ~Rule() = default; // Called on staged state AFTER each event. Must not retain references or produce // external effects; only engine state participates in the transaction. virtual bool accepts(const Inventory& proposed, const Event& event) const = 0; }; class TotalLimit final : public Rule { public: explicit TotalLimit(long maximum) : maximum_(maximum) { } // Require maximum >= 0. bool accepts(const Inventory& proposed, const Event& event) const override; private: long maximum_; }; class Engine { public: Engine() = default; Engine(const Engine&) = delete; Engine& operator=(const Engine&) = delete; Engine(Engine&&) = default; Engine& operator=(Engine&&) = default; bool add_rule(std::unique_ptr<Rule> rule); // Non-NULL owned rule; future batches only. BatchResult apply(std::span<const Event> events); Inventory snapshot() const { return state_; } // Owning copy, independent of later updates. private: Inventory state_; std::vector<std::unique_ptr<Rule>> rules_; }; // Definition stays in header for instantiation. Predicates inspect, never retain, // their argument; exceptions/external effects are outside the engine contract. template<class Predicate> requires std::predicate<Predicate, const Event&> std::size_t count_events(std::span<const Event> events, Predicate matches) { std::size_t count = 0; for (const Event& event : events) { if (std::invoke(matches, event)) { ++count; } } return count; } #endif
Check your prediction
Text
Engine checks passed

In test_engine.cpp, find the batch Create{1,"Nuts",5}, Adjust{2,-99}. The test checks three facts: the error is invalid, the index is 1, and the exported inventory equals the string saved before the batch, so the staged Nuts record is absent. Then find the limit engine near the end, where Adjust{1,1}, Adjust{1,-1} must fail with rule_rejected. Explain to yourself which line of Engine::apply each of those assertions protects.

Was this article helpful?

Your response is saved on this device.