Skip to content

Canonical Events and Deterministic Reports

The Course
•
35 min study

The parser accepts create|0007|0000|Owned, because leading zeroes do not change a number's value. It also accepts create|7|0|Owned. Both describe the same event. If the engine writes events back out, for a log, a replay file or a test expectation, which spelling should it use? If the answer is "whichever it read", two logs of the same history can differ byte for byte, and a test that compares text breaks whenever the input style changes.

A canonical form picks exactly one spelling for each value and documents it. The engine's canonical event text is create|id|quantity|name, adjust|id|delta and rename|id|name: fields in that order, decimal numbers without leading zeroes or a plus sign, a minus only for negative deltas, and the name exactly as stored. Inventory exports list id|quantity|name, one item per line, in ascending ID order. Each value then has one text, which is what makes exact comparisons meaningful.

Predict and run

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

int main() {
    std::map<int,int> inventory{{2,7},{1,5}};
    for (const auto& entry : inventory) { std::cout << entry.first << '|' << entry.second << '\n'; }
    return 0;
}
Check your prediction
Text
1|5
2|7

The initializer listed item 2 first, yet item 1 prints first. std::map keeps its elements sorted by key, and iterating it visits them in that order, whatever order they were inserted in. That is a documented guarantee, which is why the engine's Inventory is a std::map. A std::unordered_map iterates in an unspecified order that can change with the number of elements, the library version or the hash function, so an export built on one would be neither canonical nor reproducible.

Normalization through a round trip

Parsing then exporting turns any accepted spelling into the canonical one:

Leading zeroes disappear on export C++
#include <charconv>
#include <iostream>
#include <string>
#include <string_view>

struct Adjust { int id; int delta; };

bool parse_number(std::string_view text, int& value) {
    const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
    return error == std::errc{} && end == text.data() + text.size();
}

bool parse_adjust(std::string_view line, Adjust& event) {
    if (!line.starts_with("adjust|")) { return false; }
    line.remove_prefix(7);
    const auto bar = line.find('|');
    if (bar == std::string_view::npos) { return false; }
    return parse_number(line.substr(0, bar), event.id) && parse_number(line.substr(bar + 1), event.delta);
}

std::string export_adjust(const Adjust& event) {
    return "adjust|" + std::to_string(event.id) + "|" + std::to_string(event.delta);
}

int main() {
    for (std::string_view line : {"adjust|0002|-03", "adjust|2|-3", "adjust|2|0000"}) {
        Adjust event{};
        if (parse_adjust(line, event)) { std::cout << line << " -> " << export_adjust(event) << "\n"; }
    }
    return 0;
}
Text
adjust|0002|-03 -> adjust|2|-3
adjust|2|-3 -> adjust|2|-3
adjust|2|0000 -> adjust|2|0

std::to_string on an int always produces the canonical decimal form, so the canonical form is defined by the exporter, and the parser only has to accept it. The project tests exactly this with create|0007|0000|Owned, which must export as create|7|0|Owned.

Why names cannot contain the separator

A canonical format must also be unambiguous: a reader must be able to split it back into the same fields. If a name could contain |, then rename|2|Nuts|Bolts would be either a two-part name or a line with too many fields. Formats deal with this in two ways: escape the separator inside fields, or forbid it. The engine forbids it, together with leading and trailing spaces and non-printable characters, which keeps the format readable and the parser short. The cost is that some names cannot be stored, a limit the brief documents.

Exact strings and round trips catch different bugs

There are two natural tests for a format. A round trip checks that export(parse(text)) == text for canonical text. An exact-string test checks that export(event) equals a known expected string. You need both, because a round trip cannot detect two mistakes that cancel out:

Two bugs that agree with each other C++
#include <iostream>
#include <string>

std::string export_quantity(int quantity) { return std::to_string(quantity + 1); } // Bug.
int parse_quantity(const std::string& text) { return std::stoi(text) - 1; }       // Matching bug.

int main() {
    const int quantity = 10;
    const bool round_trip = parse_quantity(export_quantity(quantity)) == quantity;
    const bool exact = export_quantity(quantity) == "10";
    std::cout << "round trip " << (round_trip ? "passes" : "fails") << ", exact text " << (exact ? "passes" : "fails") << "\n";
    return 0;
}
Text
round trip passes, exact text fails

The project's mutation "wrong canonical event quantity" makes the exporter write quantity + 1. The exact assertion export_event(events[0]) == "create|7|0|Keep title" fails at once. The round-trip assertions happen to fail too, because only the exporter changed and the parser still reads the number faithfully. A matching pair of mistakes, like the one above, is the case that only exact strings catch, and it is more likely than it looks once a parser and exporter share a helper. (std::stoi is used here only to keep the demo short; with exceptions disabled, invalid text would stop the program, which is why real parsers use from_chars.)

Practice

Exercise

Your turn

Write an ExportVisitor with one overload each for Create{id, name, quantity}, Adjust{id, delta} and Rename{id, name}, returning canonical text without a newline. Then write std::string export_inventory(const std::map<int, Item>&) with Item{name, quantity}, producing id|quantity|name\n per item. Print the events Create{7,"Keep title",0}, Adjust{7,-3}, Rename{7,"Renamed"}, then export an inventory built by inserting item 2 before item 1:

Shell
create|7|0|Keep title
adjust|7|-3
rename|7|Renamed
1|5|Nuts
2|7|Bolts
Your workspace C++
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#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; };

int main() {
    // Export three events, then an inventory.
    return 0;
}
Hint 1: the idea

The field order in the text is the documented order, not the struct's member order: Create stores name before quantity but exports the quantity first.

Hint 2: a first step

Write the Adjust overload first, since it has no field-order trap, and print adjust|7|-3. Then write Create by listing the fields in the order the expected output shows them, create, id, quantity, name, before you write any code, and compare that list with the struct's declaration.

Show one solution
Run the solution C++
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#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; };

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_inventory(const std::map<int, Item>& inventory) {
    std::ostringstream output;
    for (const auto& [id, item] : inventory) { output << id << '|' << item.quantity << '|' << item.name << '\n'; }
    return output.str();
}

int main() {
    const std::vector<Event> events{Create{7, "Keep title", 0}, Adjust{7, -3}, Rename{7, "Renamed"}};
    for (const Event& event : events) { std::cout << std::visit(ExportVisitor{}, event) << "\n"; }

    std::map<int, Item> inventory;
    inventory.emplace(2, Item{"Bolts", 7});
    inventory.emplace(1, Item{"Nuts", 5});
    std::cout << export_inventory(inventory);
    return 0;
}
Text
create|7|0|Keep title
adjust|7|-3
rename|7|Renamed
1|5|Nuts
2|7|Bolts

These are the project's own expected strings, so this visitor matches engine.cpp's ExportVisitor exactly. The export has no dependence on insertion order, and every number goes through std::to_string, so equal states always produce equal text. A canonical form is not a deduplication key, though: exporting the same Adjust twice gives the same line twice, and replaying it applies it twice. The checkpoint next makes that behavior explicit while you build the input adapter.

Was this article helpful?

Your response is saved on this device.