Skip to content

Validate Against Earlier Events in the Batch

The Course
•
35 min study

Staging decides what happens to live state when a batch fails. It leaves a second question open: what does each event in the batch see? Two answers are possible. Every event could be checked against the live inventory as it was before the batch, or each event could be checked against the staged inventory, including the changes made by the events before it. The answer changes which batches succeed, so it has to be specified before it is implemented, and tested once it is.

The engine chooses the second answer. Events are ordered, each one sees the earlier staged changes, and every rule is checked after every event. That makes "create item 7, then adjust item 7" a valid batch, makes the reverse order fail, and means a temporary violation cannot be excused by a later event that compensates for it.

Predict and run

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

int main() {
    std::map<int,int> staged;
    staged.emplace(7,10);
    staged.find(7)->second -= 3;
    std::cout << staged.find(7)->second << "\n";
    return 0;
}
Check your prediction
Text
7

The adjustment found item 7 because the creation had already been staged. Reverse the two lines and staged.find(7) returns staged.end(), the past-the-end iterator. Writing ->second through it is undefined behavior, not an error you can detect afterward. That is why every handler in the engine compares the result of find with end() before using it, and reports Error::missing when the item is absent.

A lookup that silently creates

std::map::operator[] looks convenient for adjustments, and it hides exactly the failure the batch should report. When the key is missing, it inserts a value-initialized element and returns a reference to it:

operator[] invents a missing item C++
#include <iostream>
#include <map>

int main() {
    std::map<int,int> staged{{1, 10}};
    staged[7] -= 3; // Item 7 does not exist; this creates it with 0 first.
    std::cout << "items " << staged.size() << ", item 7 has " << staged.find(7)->second << "\n";
    return 0;
}
Text
items 2, item 7 has -3

The adjustment of a missing item became a creation of an item with a negative quantity, and no check ran. find makes absence explicit, and emplace or try_emplace make creation explicit, returning a flag that says whether the key was new. Use operator[] only when inserting a default really is the intended behavior.

Check after every event, not at the end

Suppose a rule limits the total quantity to 10, the inventory holds 8, and the batch is +5, -5. The final total is 8, which satisfies the rule. The intermediate total is 13, which does not. The engine rejects this batch, and the reasons are worth knowing:

  • A rule is an invariant: a statement that is true of every state the engine produces. Checking it only at the end would make it true of committed states only, and every rule author would need to know that.
  • An end-of-batch check judges the batch by its sum, not by its steps. A batch whose last event happens to restore balance could then contain any intermediate nonsense, including states no rule author ever considered.
  • Per-event checks give a precise failure point. The engine can report which event broke the rule, which is the subject of the next lesson.

The project's test suite pins this down with Adjust{1,1}, Adjust{1,-1} against a limit of 10 on an item already at 10, and expects rule_rejected.

The cost is that rules run once per event rather than once per batch. With at most 256 events and a few rules, that is cheap. A rule that must scan the whole inventory each time, like TotalLimit, costs events times items; if that ever mattered, the engine could maintain a running total instead.

Practice

Exercise

Your turn

Use struct Create { int id; int quantity; }; and struct Adjust { int id; int delta; }; in an Event variant. Write const char* apply_batch(std::map<int,int>& live, const std::vector<Event>& batch, int limit) that stages a copy, applies each event with a visitor, checks after every event that the total of all quantities is at most limit, and swaps only on success. It returns "ok", "missing", "duplicate" or "over limit". Ignore range checks for this exercise. Starting from an empty map with a limit of 10, run these batches and print each result and the number of items:

Shell
create then adjust: ok, 1 items
adjust then create: missing, 1 items
duplicate create: duplicate, 1 items
up then down: over limit, 1 items
item 7 has 7

The batches are Create{7,10}, Adjust{7,-3}; then Adjust{8,2}, Create{8,1}; then Create{7,1}; then Adjust{7,5}, Adjust{7,-5}.

Your workspace C++
#include <iostream>
#include <map>
#include <variant>
#include <vector>

struct Create { int id; int quantity; };
struct Adjust { int id; int delta; };
using Event = std::variant<Create, Adjust>;

int main() {
    std::map<int,int> live;
    // Write apply_batch and run the four batches.
    return 0;
}
Hint 1: the idea

Each event and the limit check see the staged map as the events before it left it. Any failure returns before the swap.

Hint 2: a first step

Write a visitor struct Apply { std::map<int,int>& staged; const char* operator()(const Create& e) const { return staged.emplace(e.id, e.quantity).second ? "ok" : "duplicate"; } ... };.

Show one solution
Run the solution C++
#include <iostream>
#include <map>
#include <string_view>
#include <variant>
#include <vector>

struct Create { int id; int quantity; };
struct Adjust { int id; int delta; };
using Event = std::variant<Create, Adjust>;

struct Apply {
    std::map<int,int>& staged;
    const char* operator()(const Create& event) const {
        return staged.emplace(event.id, event.quantity).second ? "ok" : "duplicate";
    }
    const char* operator()(const Adjust& event) const {
        auto found = staged.find(event.id);
        if (found == staged.end()) { return "missing"; }
        found->second += event.delta;
        return "ok";
    }
};

long total(const std::map<int,int>& items) {
    long sum = 0;
    for (const auto& entry : items) { sum += entry.second; }
    return sum;
}

const char* apply_batch(std::map<int,int>& live, const std::vector<Event>& batch, int limit) {
    auto staged = live;
    for (const Event& event : batch) {
        const char* result = std::visit(Apply{staged}, event);
        if (std::string_view(result) != "ok") { return result; }
        if (total(staged) > limit) { return "over limit"; }
    }
    live.swap(staged);
    return "ok";
}

int main() {
    std::map<int,int> live;
    const int limit = 10;
    std::cout << "create then adjust: " << apply_batch(live, {Create{7,10}, Adjust{7,-3}}, limit);
    std::cout << ", " << live.size() << " items\n";
    std::cout << "adjust then create: " << apply_batch(live, {Adjust{8,2}, Create{8,1}}, limit);
    std::cout << ", " << live.size() << " items\n";
    std::cout << "duplicate create: " << apply_batch(live, {Create{7,1}}, limit);
    std::cout << ", " << live.size() << " items\n";
    std::cout << "up then down: " << apply_batch(live, {Adjust{7,5}, Adjust{7,-5}}, limit);
    std::cout << ", " << live.size() << " items\n";
    std::cout << "item 7 has " << live.find(7)->second << "\n";
    return 0;
}
Text
create then adjust: ok, 1 items
adjust then create: missing, 1 items
duplicate create: duplicate, 1 items
up then down: over limit, 1 items
item 7 has 7

The same two events succeed in one order and fail in the other, and the last batch fails although its net effect is zero, because the staged total reached 12 after its first event. Comparing const char* results with != would compare pointers, not text, which is why the solution wraps the result in std::string_view. A returned string is a poor result type for anything bigger than an exercise, though: it cannot say which event failed. The next lesson replaces it with an error enum and an optional index.

Was this article helpful?

Your response is saved on this device.