RUSTYCMDGAMES
RustyCMD Games
Explore Packet EmpireJoin the Discord

A little rust. A lot of systems.

Devlog

How I Replay Every Bug Report: Building a Deterministic Simulation Game

How Packet Empire's deterministic simulation replays any bug report exactly: fixed ticks, integer money, a seeded RNG and every action logged as a command.

A DDoS wave hitting a Packet Empire floor: a Firewall behind every Uplink filters out the malicious packets before they reach the Parsers and Ports

When someone presses F8 in Packet Empire, the game writes a small zip: their save, their recent log, and every action they took in the last few minutes. I feed that zip to a headless copy of the game, built from the exact version that made the report, and watch the bug happen again, tick for tick. At the end, the replay’s state hash either matches the save in the zip or it doesn’t. When it matches, I’ve reproduced the session exactly.

That only works because the simulation is deterministic: the same starting state plus the same inputs gives the same result, every time, on any machine. This post covers how that’s built, the rules that keep it true, and what it costs. The game itself is a factory game crossed with a data-centre tycoon, written in TypeScript, where glowing data packets flow through machines you wire together on a grid.

Why a deterministic simulation is worth the trouble

Bug reports for systems games are hard to act on. “My line jammed after the DDoS, I think?” is an honest report, but a factory’s state is large and emergent, and the cause is often minutes old by the time anyone notices. Reproducing it by hand means guessing.

Deterministic lockstep is the technique many strategy and factory games use for multiplayer: instead of syncing the whole world, every computer receives the same inputs and computes the same world. Packet Empire is single-player, but the same property gives you something just as useful. If the simulation is deterministic, a recording of the inputs is a recording of the whole game. Replays, regression tests and undo all fall out of it.

I decided this on day one, before the first tick ran, because retrofitting determinism into a game that wasn’t built for it is miserable.

The shape: a pure simulation in a Web Worker

The golden rule is that the simulation knows nothing about graphics, UI, Electron or Steam.

  • The sim runs in a Web Worker at a fixed 20 ticks per second. The game state lives only there.
  • The main thread never holds or changes the state. It receives snapshots: packet positions as transferable typed arrays every tick, and a UI summary (money, contracts and so on) at most 10 times a second.
  • The renderer interpolates between the last two snapshots, so the floor animates smoothly at 60 to 144 fps while the sim ticks at 20.
  • The same sim code runs in Node, with no worker, for unit tests, the replay tool and a balance bot that plays the real simulation for hours (roughly two seconds of real time per simulated hour).

The worker helps speed (on my heaviest test scene the average tick takes about 0.12 ms against a 4 ms budget), but it also keeps the sim honest: a worker has no DOM, and a lint rule lets the sim import only itself, the game’s data and the RNG.

Every player action is a Command

Placing a machine, drawing a cable, accepting a contract, answering an email: everything the player does becomes a Command. Commands are posted to the worker, queued, applied at the start of the next tick, and logged.

// Illustrative: the shape of the idea, not the game's source.
type Command =
  | { type: 'place'; machine: MachineKind; x: number; y: number; rot: Rotation }
  | { type: 'cable'; from: PortRef; to: PortRef }
  | { type: 'accept'; offerId: number }
  | { type: 'setSpeed'; speed: 0 | 1 | 2 };

function step(state: GameState, queued: Command[]): void {
  for (const cmd of queued) applyCommand(state, cmd); // inputs first, always
  runSystems(state);                                  // fixed order, integers only
  state.tick += 1;
}

A few less obvious ones:

  • Game speed. Since v0.10.1, running at 2× costs extra power and heat, so the speed change has to enter the simulation. Otherwise a replay would run at 1× and get a different power bill.
  • Undo and redo. These are recorded inverse commands kept in the game state, so they’re deterministic and replayable like anything else.
  • Unlocking a demo save. When a save from the free demo is opened in the full game, a command lifts the demo’s limits. More on that below.

The tick order is fixed too: apply commands, then power, heat, machines, cables, deliveries and contracts, events, research, and the economy settlement every 20th tick.

The determinism rules, and why each one exists

A fixed tick

Each tick is 50 ms of game time, always. A variable time step makes the outcome depend on the frame rate, which depends on the player’s graphics card. Playing at 2× runs more ticks, never bigger ones.

Integers only in the game state

Money is whole integer cents. Packet progress along a cable is an integer in 1/1024ths of a tile. Machine temperatures are whole degrees. The save schema rejects any number that isn’t an integer.

JavaScript’s basic arithmetic on doubles is IEEE 754 and gives the same answer for the same operations in the same order. The catch is the order: floating-point addition isn’t associative, so (a + b) + c can differ from a + (b + c) in the last bit. Reorder a loop during a refactor and the results drift, and in a factory game small drifts compound. Integers within the safe range are exact whichever way round you add them. They also survive a trip through a JSON save byte for byte.

Money gets extra care. Income is settled once per second, rates are integer cents per second, and multipliers are integer basis points (10,000 means ×1.0). Each income source carries a remainder, so no fraction of a cent is ever lost or invented:

// Pay one income source for one second.
// rateCents: integer cents per second. multBp: 10_000 = x1.0, 12_500 = x1.25.
function settle(src: IncomeSource, rateCents: number, multBp: number): number {
  src.remainder += rateCents * multBp;
  const pay = Math.floor(src.remainder / 10_000);
  src.remainder -= pay * 10_000;
  return pay; // whole cents; the leftover fraction waits for the next second
}

Every payment lands in a ledger category, and an invariant checks that money always equals the starting money plus the sum of the ledger. The economy is deliberately tycoon-sized: a run peaks around $1 trillion, a JavaScript number holds whole cents exactly up to about $90 trillion, and anything past $10 trillion logs an error as a design bug.

No transcendental Math functions

The ECMAScript spec leaves Math.sin, Math.exp, Math.pow and friends “implementation-approximated”, and JavaScript engines have changed their implementations between versions. My replay tool runs in Node while the game runs inside Electron’s Chromium, and nothing guarantees they share a V8 version. So the sim bans sin, cos, tan, exp, log, pow, atan2, hypot and the rest. floor, ceil, round, trunc, min, max, abs, sign, imul and clz32 are allowed, and small integer powers go through a helper.

That shapes the design. Heat spreads from each machine to its neighbours with a square, integer falloff instead of a smooth radial curve, and nothing in the sim uses trigonometry. The renderer can use whatever maths it likes, because nothing it computes goes back into the state.

A seeded RNG that lives in the save

There’s no Math.random in the sim. Randomness comes from a seeded xoshiro128** generator whose state is stored in the game state, so saving and loading picks up the exact same sequence.

One shared stream has a side effect worth knowing about: every new draw shifts every later draw. When the Inbox arrived in v0.20.0 and started drawing from the sim RNG, it reshuffled every later roll for offers and events. My balance bot’s median time to finish the free demo jumped from about 56 to about 76 minutes on the same seeds (75 with the mail switched off, so it wasn’t the mail choices themselves). I re-tuned the demo in the next version. These days new RNG use stays inside the new system, and any change like that bumps a sim version number that saves and replays both record.

The simulation never sees the clock

No Date, no performance.now. The sim only knows ticks. Back when the game had offline earnings, the time you’d been away entered as a command carrying a number of seconds, so even that was replayable. Offline earnings were removed in v0.12.0 for economy reasons (why I removed offline earnings), and now nothing happens while the game is closed. Angel investments, events and golden packets all run on play time.

Stable iteration order

Entities live in arrays or Maps keyed by incrementing integer ids, and are walked in id order. Plain object keys are a trap: JavaScript puts integer-like keys first in ascending order and string keys after them in insertion order, so a mixed-key object iterates in an order that depends on what the keys happen to look like.

What happens when you press F8

Press F8 (the default key; it’s rebindable) or choose Report a bug in the pause menu. The game can ask for a one-line note about what went wrong, then writes a zip to a bug-reports folder on your Desktop containing:

  • the log: the last 5,000 structured log entries, with every command at debug level;
  • the save;
  • the replay: the last few minutes of commands, plus the checkpoint they start from;
  • a screenshot;
  • system info: the game version, the exact code version it was built from, the sim version, hardware and settings;
  • your note, if you wrote one.

The zip stays on your PC until you choose to send it. Online crash reports are a separate, opt-in setting, and they never upload the bundle.

Replaying it headless

On my side, one command takes the zip and:

  1. prints the note, the versions and any warnings or errors from the log;
  2. if the report came from an older build, checks out the exact version of the game that made the report and runs the replay there (every build is stamped with the version it was built from, which is why I only build from committed code);
  3. loads the checkpoint and re-runs the commands with invariant checks every tick: no negative stock, packets conserved, money matching the ledger;
  4. compares the final state hash with the save in the bundle. MATCH means the session was reproduced exactly.

If the version is unknown, the tool refuses to run unless forced, and prints a loud warning if the sim version differs. Then the routine is always the same: reproduce, write a failing test, fix, and watch it pass.

One design choice made this work for the free demo too. The demo’s limits are stored in the save, not baked into the build, so a bug report from the demo replays exactly in any build.

Hashes as a safety net

The same machinery catches mistakes before they ship. Golden replays are scripted scenarios (“build a starter webpage line”) that run for a set number of ticks and compare a state hash, on every change. They catch accidental balance and logic shifts, and they prove when a refactor changed nothing. When the heat formula moved into a module shared by the sim and the placement preview, every golden hash stayed the same. When difficulty levels and the demo were added, I ran the old scenarios with the new fields at their neutral values first, and every hash matched the previous version.

Even the marketing footage leans on it. Trailer clips are captured frame by frame from a scripted replay, and the worker’s state hash confirms the footage matches the headless run, so what you see in a clip is what the game really does.

What it costs, and what it doesn’t catch

  • Discipline, everywhere. Every feature has to answer “does this change results?” before it lands. If it does, the sim version goes up, and if the save’s shape changes, there’s a tested migration so old saves still load.
  • Replays reproduce the simulation, not the pixels. A rendering bug, like the main-menu background that went black after tabbing out with Reduce motion on (an F8 report fixed in v0.7.2), lives outside the sim. For those, the screenshot, the log and the system info do the work.
  • The window is a few minutes. A problem that started an hour earlier is still in the save, but the replay won’t show the moment it began.
  • A crash mid-tick is caught. The game pauses, the last good autosave is protected, and you’re offered a report. Losing progress to a crash would break another rule of mine: nothing is ever destroyed.

Replay first, guess never

Packet Empire is made by one developer (the whole QA department is me), and determinism is what lets one person keep up with bug reports. The standing rule is to replay the zip before guessing, turn it into a failing test, then fix it. A bug that can be replayed doesn’t depend on anyone’s memory of what happened.

If you’re starting a systems-heavy game, make the call on determinism before the first tick runs. It’s a handful of rules that are cheap on day one and very expensive on day three hundred. And if you play my free demo when it arrives and something breaks, an F8 zip in my Discord is the most useful bug report you could send.

Keep reading