Skip to content

Generate Reproducible Event Sequences

The Course
•
35 min study

A reference model is only as good as the inputs you feed it. Generated inputs reach cases nobody would write by hand, such as three adjustments that dip below zero and come back. But a generated test that fails once and then passes on the next run, because the inputs changed, is worse than no test: it tells you a bug exists and gives you no way to find it. The fix is to make generation deterministic. A seed fully determines the sequence, so the same seed always produces the same batches, and a failure report that includes the seed and the iteration is a complete recipe for reproducing it.

The project's test generates 500 batches of three adjustments from seed 12345, with deltas between -20 and 20, and compares the engine with the model after every batch. This lesson explains why its generator is written the way it is.

Predict and run

Predict before running C++
#include <iostream>

int main() {
    unsigned long seed = 12345;
    for (int i = 0; i < 3; ++i) {
        seed = (seed * 1103515245UL + 12345UL) & 0x7fffffffUL;
        std::cout << (int)(seed % 41) - 20 << "\n";
    }
    return 0;
}
Check your prediction
Text
-3
18
13

Nobody predicts these numbers by mental arithmetic, and that is the point: they look arbitrary, but they are fixed. Run it again, on any machine, and you get -3, 18, 13. Change the seed to 12346 and you get a different, equally fixed sequence. This is a linear congruential generator: multiply, add, keep the low 31 bits. seed % 41 maps the state to 0..40, and subtracting 20 gives -20..20.

Why not rand or random_device

  • std::rand() is reproducible on one platform, but its algorithm is not specified, so the same seed gives different sequences on different standard libraries. A failure seen in CI on Linux may not reproduce on a Mac.
  • std::random_device is meant to be unpredictable. That is right for keys and wrong for tests.
  • std::mt19937 is specified exactly, so its raw outputs are portable. The distributions such as std::uniform_int_distribution are not: each library may map raw numbers to a range differently. Portable tests use the engine's raw output and their own mapping.
  • Clocks, thread timing and memory addresses all change from run to run. None of them belong in a test's inputs.

The hand-rolled generator avoids all of that with three lines of arithmetic whose result is defined by the language itself.

Unsigned wraparound is defined; signed overflow is not

seed * 1103515245UL overflows. For unsigned types that is fine: the standard defines unsigned arithmetic modulo 2 to the power of the type's width, so the result wraps predictably. The same overflow on a signed long would be undefined behavior, and an optimizer is allowed to assume it never happens.

There is a portability catch: unsigned long is 64 bits on Linux and macOS but 32 bits on Windows and in 32-bit WebAssembly. The mask & 0x7fffffff makes that harmless. The low 31 bits of a product or sum depend only on the low 31 bits of the inputs, so whether the arithmetic wrapped at 32 or 64 bits, the masked result is identical:

Same sequence at two widths C++
#include <cstdint>
#include <iostream>

int main() {
    std::uint32_t narrow = 12345;
    std::uint64_t wide = 12345;
    bool same = true;
    for (int i = 0; i < 1000; ++i) {
        narrow = (narrow * 1103515245u + 12345u) & 0x7fffffffu;
        wide = (wide * 1103515245u + 12345u) & 0x7fffffffu;
        same = same && narrow == wide;
    }
    std::cout << "1000 steps identical: " << same << ", last " << narrow % 41 << "\n";
    return 0;
}
Text
1000 steps identical: 1, last 16

This generator has poor statistical quality, and the modulo slightly favors some values. Neither matters for a test that only needs varied, reproducible inputs. It would matter for a simulation, and it would be unacceptable for anything security-related.

Make failures actionable

When a seeded comparison fails, report everything needed to reproduce and understand it: the seed, the iteration, the state before the batch, and the batch itself. Then two follow-ups pay off:

  • Turn it into a fixed test. Copy the failing batch into a hand-written case, so it stays covered even if the generator changes.
  • Shrink it. Try removing events or moving values toward zero while the failure persists. A three-event batch is already small; for long sequences, the smallest failing input is usually the clearest explanation.

Also try more than one seed. As the practice shows, a seed can miss a bug that another seed finds in its first few batches, which is why running many seeds in a longer test, while keeping one fixed seed in the quick suite, is common practice.

Practice

Exercise

Your turn

Write int next_delta(unsigned long& seed) using the project's generator. Then write void run(unsigned long seed) that generates 500 batches of three deltas, compares the model with the buggy final_only engine from the starter, both starting at 10 and carrying their own state, and reports the first disagreement or a pass. Run seeds 12345 and 2024, then 12345 again:

Shell
seed 12345: failed at iteration 28 from 18: -15 -10 15
seed 2024: passed 500 batches
seed 12345: failed at iteration 28 from 18: -15 -10 15
Your workspace C++
#include <iostream>
#include <vector>

struct Outcome { bool accepted; int quantity; };

Outcome model(int quantity, const std::vector<int>& deltas) {
    int candidate = quantity;
    for (int delta : deltas) {
        candidate += delta;
        if (candidate < 0 || candidate > 1000) { return {false, quantity}; }
    }
    return {true, candidate};
}

Outcome final_only(int quantity, const std::vector<int>& deltas) { // Checks only the end.
    int candidate = quantity;
    for (int delta : deltas) { candidate += delta; }
    if (candidate < 0 || candidate > 1000) { return {false, quantity}; }
    return {true, candidate};
}

int main() {
    // Write next_delta and run, then try the three seeds.
    return 0;
}
Hint 1: the idea

The generator's state is the seed, passed by reference so each call advances it. Everything else in run is the comparison loop from the previous lesson.

Hint 2: a first step

seed = (seed * 1103515245UL + 12345UL) & 0x7fffffffUL; return static_cast<int>(seed % 41) - 20;

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

struct Outcome { bool accepted; int quantity; };

Outcome model(int quantity, const std::vector<int>& deltas) {
    int candidate = quantity;
    for (int delta : deltas) {
        candidate += delta;
        if (candidate < 0 || candidate > 1000) { return {false, quantity}; }
    }
    return {true, candidate};
}

Outcome final_only(int quantity, const std::vector<int>& deltas) { // Checks only the end.
    int candidate = quantity;
    for (int delta : deltas) { candidate += delta; }
    if (candidate < 0 || candidate > 1000) { return {false, quantity}; }
    return {true, candidate};
}

int next_delta(unsigned long& seed) {
    seed = (seed * 1103515245UL + 12345UL) & 0x7fffffffUL;
    return static_cast<int>(seed % 41) - 20;
}

void run(unsigned long seed) {
    const unsigned long initial = seed;
    int expected = 10, actual = 10;
    for (int iteration = 0; iteration < 500; ++iteration) {
        std::vector<int> batch;
        for (int j = 0; j < 3; ++j) { batch.push_back(next_delta(seed)); }
        const Outcome want = model(expected, batch);
        const Outcome got = final_only(actual, batch);
        if (want.accepted != got.accepted || want.quantity != got.quantity) {
            std::cout << "seed " << initial << ": failed at iteration " << iteration << " from " << expected << ":";
            for (int delta : batch) { std::cout << " " << delta; }
            std::cout << "\n";
            return;
        }
        expected = want.quantity;
        actual = got.quantity;
    }
    std::cout << "seed " << initial << ": passed 500 batches\n";
}

int main() {
    run(12345);
    run(2024);
    run(12345);
    return 0;
}
Text
seed 12345: failed at iteration 28 from 18: -15 -10 15
seed 2024: passed 500 batches
seed 12345: failed at iteration 28 from 18: -15 -10 15

From 18, the batch reaches 3, then -7, then 8. The model rejects it at -7; the buggy engine sees only the final 8 and accepts. Running seed 12345 again reproduced the failure exactly, which is the whole point of seeding. Seed 2024 never produced a dip below zero that recovered, so it passed a broken engine: one seed is a sample, not a guarantee. The checkpoint next turns this question around and asks, for each deliberate bug, whether some test catches it.

Was this article helpful?

Your response is saved on this device.