Skip to content

cat posts/en/atlantis-pbem-neu-geschrieben-12-der-zustand-nach-jeder-phase.md

Atlantis PbeM Rewritten (Part 12): The state after every phase

Before the port executes its first order, the C++ reference writes 32 states: right before RunOrders and after each of its 31 phases. Part 12 shows why saving alone would have changed the turn—and how to check that the observation itself changes nothing.

Sepia chronophotograph: In eight frames across two rows, a white cat runs through successive phases of motion in front of a dark curtain.

After part 11, the Python port can generate, load, and save a world, read orders, and write reports.

It still can't play, though.

A turn in Atlantis PbeM starts with the engine reading the orders of all factions. Then Game::RunOrders works through them in a fixed sequence: finding, entering and leaving buildings, combat, stealing, giving, taxes, trade, movement, month-long orders like studying and working, the economy, and more phases. At the end, the new game state comes out as game.out.

Step 11 of the roadmap ports this turn processing piece by piece.

Step 11.0 comes first.

It ports no game logic. Instead, it builds the measuring instrument we need for that job: states between the phases.

When the reference and the port drift apart later, we don't just want to know that they end up with a different game state. We want to see from which phase on it happens.

A comparison at the end of the turn isn't enough

The comparison harness from part 3 already knows the principle: a game.out is converted into state.json and compared as structured state.

For processing a complete turn, though, a single state at the end is too coarse.

RunOrders calls about 40 functions. Combat, the economy, and other parts of the turn draw random numbers from the same generator whose stream the port has reproduced exactly since part 4.

If the Python port draws one time too many in combat, for example, everything after it shifts. A later monster decision can be wrong even though the actual bug was in combat, many phases earlier.

At the end, you see a big deviation.

You don't see the cause.

World generation in part 8 had the same problem. There, eight intermediate states helped narrow down the first deviation.

For a turn, we need the same principle at a finer resolution.

This time the oracle has to change

The C++ reference can't write intermediate states like these yet.

And normally, that very reference is off-limits in this project. It sits as a submodule under reference/ and defines the behavior the Python port is checked against.

So the instrumentation doesn't belong in the port, and it doesn't belong in the submodule as a local patch either. It has to go into the fork geekblogio/atlantis-pbem-engine, under that fork's own rules.

The fork already has environment variables for optional fork features, ATLANTIS_SEED for example. They're read in main.cpp, do nothing when unset, and show up in the command-line help.

The new switch follows the same pattern:

ATLANTIS_PHASE_DUMPS

The fork's published interface under docs/interface/ gets updated in the same pull request, too. And like every deviation of the fork from upstream, this one gets an entry in docs/fork/patches.md.

The opt-in is important. Without the variable set, nothing at all should change for existing users of the fork, least of all for its snapshot tests and the other downstream projects.

31 phases, 32 states

RunOrders already has a usable structure.

The code contains 31 messages like this one:

// reference/runorders.cpp
logger::write("Running Combat...");
DoAttackOrders();
DoAutoAttacks();

Each message marks a section of the turn.

Some of them contain several function calls. Five sections depend on ruleset settings: WITHDRAW, SACRIFICE, TRANSPORT, ANNIHILATION, and MIGRATION.

In standard, WITHDRAW runs and the other four are skipped.

Three functions after movement, on the other hand, have no log line of their own at all:

SinkUncrewedFleets
DrownUnits
FindDeadFactions

So they belong to the movement phase, together with RunMovementOrders.

Before RunOrders, there's one more state:

00-orders

It's written after ReadOrders and RemoveInactiveFactions, right before the actual turn processing begins.

After that come the 31 phases, from

01-find

to

31-post-turn

That makes 32 files per turn.

The distinction is small but important: 00-orders isn't another RunOrders section. It's the starting state the first phase can be compared against.

The numbers are part of the interface

A second decision was just as important:

The 32 names are fixed.

Even if a ruleset doesn't run an optional phase, the corresponding file still gets written. It then simply holds the same world state as the previous checkpoint.

standard, for example, skips sacrifice but still writes:

phase.21-sacrifice.out

That way, a consumer doesn't need to know any ruleset settings to find a particular phase.

phase.22-movement.out always means: the state after movement.

A skipped phase doesn't shift any numbers.

For a comparison tool in particular, that stability is worth more than a few saved files.

Why SaveGame is useless here

The obvious approach would have been to just call Game::SaveGame after every phase.

But that would have changed the very turn we want to observe.

We know the seed line of game.out from part 9.

SaveGame doesn't write the generator's current state there. It draws a new random number:

// reference/game.cpp
rng::get_random(10000)

The next time the game is loaded, that value is used as the seed again.

32 extra SaveGame calls during a turn would therefore use up 32 extra random draws.

After that, the random stream would be shifted.

The phase files would document a turn that only played out that way because of the phase instrumentation.

That would be pretty much the opposite of an oracle.

Writing without a draw

So before the fork was changed, the writers involved were checked: faction.cpp, aregion.cpp, object.cpp, unit.cpp, items.cpp, skills.cpp, market.cpp, production.cpp, quests.cpp, and game.cpp.

On this write path, the only RNG draw is in SaveGame.

So the fork separates the actual serialization from generating the next seed:

// reference/game.cpp
int Game::SaveGame()
{
    std::ofstream f("game.out", std::ios::out|std::ios::ate);
    if (!f.is_open()) return(0);

    // The one draw of saving: it seeds the next turn (OpenGame). Nothing write_game calls draws,
    // so taking it before the first line leaves the stream of draws as it was.
    write_game(f, rng::get_random(10000));
    return(1);
}

write_game now gets the seed to write as an argument.

The normal SaveGame still behaves as before: exactly one draw.

For a phase state, there's this instead:

// reference/game.cpp
void Game::dump_phase(int number, const std::string& name)
{
    if (!phase_dumps) return;

    // ...

    // The seed line is a placeholder. Drawing one here, as SaveGame does, would move every draw
    // after it and change the turn being recorded.
    write_game(f, 0);
}

So the seventh line of every phase file contains:

0

That's explicitly not a seed.

It's only a placeholder, so the file keeps the same positional format as game.out.

The alternative would have been to save the internal RNG state, draw a seed, and restore the state afterward.

That would produce a value that looks real, but for something that never gets loaded as a game state. On top of that, the instrumentation would have to reach deeper into the random number generator.

The placeholder is simpler and more honest.

A dump right next to the phase

In RunOrders, the instrumentation ends up looking unspectacular:

// reference/runorders.cpp
logger::write("Running Consolidated Movement Orders...");
RunMovementOrders();

SinkUncrewedFleets();
DrownUnits();
FindDeadFactions();
dump_phase(22, "movement");

31 calls like this sit right at the 31 phases.

00-orders is written earlier, in RunGame.

So the phase and its dump live in the same source code. There's no second list that tries to reconstruct the control flow of RunOrders after the fact.

Does the instrumentation really leave the turn alone?

You can confirm in the code that dump_phase itself draws no random number.

For instrumenting the oracle, though, that alone isn't enough for me.

So the fork also checks the claim against its recorded turns.

A new unit test suite checks write_game: the writer draws nothing itself, writes the same text for the same state, and puts the value it's given into the seed line.

The snapshot test is more important.

run-phase-dump-snapshot.sh replays all 14 recorded turns of the standard game, this time with ATLANTIS_PHASE_DUMPS set.

Every turn produces all 32 additional files.

The existing game files, reports, and templates still match the snapshots byte for byte. The console output only gains the line announcing the enabled switch.

A run without the variable produces no phase files.

That's no mathematical proof that instrumentation can never have a side effect. For the 14 recorded turns, though, it shows directly that the enabled output doesn't change the observable course of the game.

An extra RNG draw would have shown up especially fast: it would have shifted the later random stream and, at the very least, changed the seed line of game.out.

5.5 MB for one turn

For turn 13, the fork writes 32 phase files totaling about 5.5 MB.

The last one is interesting:

phase.31-post-turn.out

In this turn, it differs from the later game.out only in the seed line:

0

versus

9429

That doesn't mean, though, that the two files always have to be identical except for the seed.

After RunOrders, the turn isn't completely over yet. Among other things, RunGame writes reports, empties the holding area for dead units, and removes eliminated factions before main.cpp finally calls SaveGame.

In turn 13, these steps apparently no longer change the saved world state.

In another turn, they could.

A pull request under the fork's rules

The change itself is technically fairly small. Two organizational details of the fork are more interesting.

Its Divergence Register requires the number of the corresponding pull request for every fork patch.

But you only know that number once the pull request has been opened.

So the entry first went into the branch with #NN. The pull request got number 85, a second commit replaced the placeholder, and only then did the Divergence Register job turn green.

Chicken, egg, two commits.

A second rule concerns GitHub itself. Every gh call for this fork explicitly includes:

--repo geekblogio/atlantis-pbem-engine

The CONTRIBUTING.md documents why: without the explicit flag, a pull request once ended up upstream instead of in the fork.

The finished PR #85 changed 18 files and added 476 lines: implementation, tests, decision 0025, and the updated interface documentation combined.

The files become state dumps

After the merge, the Python project's submodule moves to the new version.

The harness can now read the phase files with the same converter it already uses for game.out.

In the JSON, a phase dump differs in two places:

# tools/compare/state.py
"point": {"year": year, "month": month, "phase": phase},
# ...
"seed": seed if phase == END else None,

point.phase holds, for example:

04-combat

For phases, the seed deliberately becomes JSON null.

Otherwise the 0 from the source file would look like a real seed, even though it only holds the format together at that position.

So:

phase.04-combat.out

becomes:

state.04-combat.json

The harness's normal artifact comparison needs no special logic for this. As soon as the files are in the turn directory, it treats them like the turn's other results.

Then it got expensive

The first version of the harness turned on phase dumps for every run.

That sounded reasonable at first. More observation helps, after all.

Then came the measurements.

A turn in the harness took about 14 seconds. A single turn directory grew to about 132 MB: 32 raw phase files of about 550 KB each, plus 32 JSON dumps of about 3.3 MB each.

build/compare reached 1.5 GB.

A single selfcheck test took about 150 seconds, and the reference tests from test_compare.py took 5 minutes and 26 seconds together.

The C++ engine itself wasn't even the main problem. Timed directly, a turn took 5.6 to 6.8 seconds with the extra files and 5.3 to 5.4 seconds without them.

The conversion afterward costs more. A state dump takes about 0.18 seconds. 32 of them add up to just under six seconds per turn on their own.

And the Python port can't run a single turn phase yet.

So the extra work would make every normal run more expensive without being able to narrow down a single deviation between the two engines for now.

The consequence:

uv run tools/compare/cli.py selfcheck --phases idle

Phases are opt-in in the harness, too.

--phases works with run and selfcheck. Without the option, the previous behavior stays as it was.

A red test that was right

The new reference test runs the idle scenario for one turn three times: twice with phase dumps, once without.

The two instrumented runs have to be identical to each other. Compared to the normal run, exactly 64 files are added: 32 phase.*.out and 32 state.*.json.

The test also alters phase.04-combat.out afterward and requires the comparison to report exactly that one artifact as changed.

The first run failed anyway.

Not because of the world.

Because of the console output.

With the switch enabled, the C++ engine writes:

Writing the world after every phase (ATLANTIS_PHASE_DUMPS).

The fork change had added this line on purpose and accounted for it in the fork's snapshot test.

The test in the Python project had forgotten about it all the same.

Instead of normalizing the line away, the test now pins the difference down explicitly:

# tests/tools/test_compare.py
[console] = [d for d in without.differences if d.kind != Kind.ONLY_LEFT]
assert (console.turn, console.artefact, console.kind) == (1, ENGINE_OUTPUT, Kind.CHANGED)
announcement = b"Writing the world after every phase (ATLANTIS_PHASE_DUMPS).\n"
first_console = normalize_console((turn / ENGINE_OUTPUT).read_bytes())
assert first_console.replace(announcement, b"", 1) == normalize_console(
    (plain / "turn_1" / ENGINE_OUTPUT).read_bytes()
)

There has to be exactly one changed console file.

Remove exactly the announced line, and the outputs have to match again.

If a second deviation sneaks in later, the test fails.

That's more useful than yet another normalization rule that simply makes the difference invisible.

Two repositories share the same table

The names of the 32 checkpoints now live in two places.

In the fork, docs/interface/file-formats.md documents the public interface.

In the Python harness, the PHASES tuple holds the same names.

Two hand-maintained lists in two repositories would drift apart sooner or later.

So a fast test reads the table straight from the pinned submodule:

# tests/tools/test_state.py
def test_the_phases_are_the_fork_s_table() -> None:
    """``PHASES`` is the table of the pinned fork's file-formats.md, in its order."""
    table = re.findall(r"^\| `(\d\d-[a-z0-9-]+)` \|", FILE_FORMATS.read_text(encoding="utf-8"), re.MULTILINE)
    assert tuple(table) == PHASES
    assert [int(phase[:2]) for phase in PHASES] == list(range(len(PHASES)))

If the fork moves a phase or adds one, the contradiction shows up at the next submodule bump.

Without this test, the harness could easily overlook a renamed phase file, because it only looks for the names it knows itself.

What the intermediate states don't show

The phase files deliberately use the game.out format.

That means they inherit its limits as well.

Order slots, battle reports, events, and error messages aren't part of this persisted world state. Some of them exist only in memory during the turn and only show up later in the reports.

So a deviation there won't necessarily be visible in the very next phase file.

That's not a forgotten extension but a deliberate limit of the instrumentation. A dedicated JSON dump straight from memory could contain more, but it would create a second serialization of the world that would have to be maintained alongside game.out.

So for this step, game.out stays the shared format.

The roadmap got sharper on this point, too. Before, it said the reference "emits the state dump".

More precisely:

The reference writes a world in the game.out format after every checkpoint.

The harness turns it into state.<phase>.json.

Pitfalls

  • Observing can change what you observe. SaveGame would have seemed like the obvious dump, but it would have used up one RNG draw per call.
  • Instrumentation needs a test against side effects. Here, a code check of the writer and 14 snapshot replays with phase dumps enabled complement each other.
  • Checkpoints need stable names. Even a skipped phase writes its file. That keeps 22-movement the same point across rulesets and turns.
  • Measure before a diagnostic tool becomes the default. The C++ output itself costs relatively little; 32 extra JSON conversions and their files are what make the harness run expensive.
  • Don't normalize unexpected differences by reflex. The extra console line is intentional, so it gets checked explicitly.
  • Duplicated interfaces need a drift test. The harness's phase list is checked against the published table of the pinned fork.
  • Documentation from memory isn't measurement. A first draft wrongly counted withdraw among the phases standard skips and contained estimated timings. Both were corrected before the review, against the code and against measurements, respectively.
  • Tool traps don't go away on their own. Once again, a Python script passed through a Bash heredoc turned a \n inside a byte string into a real line break and produced a syntax error.

Where things stand after part 12

On request, the C++ reference can now write 32 intermediate states per turn: 00-orders right before RunOrders, and then one after each of its 31 phases.

The harness converts these files into structured state dumps and compares them like the other artifacts of a turn.

In the fork, pull request #85 changed 18 files for this and added 476 lines. In the Python project, nine files changed; 317 lines were added and 41 removed. Nothing changed under src/.

590 fast tests run, three of them added in this step. 32 tests run against the built reference, one of them new.

Porting coverage drops slightly as a result, from 54.3 to 54.2 percent.

No game logic was ported in this step. The pinned C++ fork merely grew by 63 relevant lines, which now also count in the porting map's denominator.

The Python port didn't need a new decision. Its behavior doesn't change. The instrumentation is documented in the fork as decision 0025.

What's still missing is the other side of the comparison.

The Python port doesn't write phase dumps yet, because it doesn't run a turn yet.

That starts with Step 11.1: the first instant orders.

As soon as the port processes a phase itself, there will be two state.<phase>.json files for the same point in the turn for the first time.

And if they differ, we won't only find out at the end that something went wrong.

We'll know where it started.

Further reading

Sources: runorders.cpp, game.cpp, main.cpp, decision 0025, and file-formats.md of the fork, pull request #85.

0 comments

No comments yet. Be the first!