DEV Community

Aman Kumar
Aman Kumar

Posted on Originally published at dev.to

Building Deterministic Lockstep Simulation Engines with Python and NumPy

Why Floating-Point Breaks Distributed Replays

In multiplayer physics, distributed simulation testing, or algorithmic trading backtesting, reproducibility is paramount. If two instances execute the same sequence of actions on the same initial state, their end states must be bit-for-bit identical.

Standard IEEE 754 floating-point operations fail this test across different CPU architectures, OS kernels, and compiler optimization flags. An x86_64 machine with FMA (Fused Multiply-Add) produces subtly different rounding results compared to an ARM64 Apple Silicon or AWS Graviton processor.

The solution is Deterministic Lockstep Simulation driven by integer or fixed-point mathematics.

Architecture

+---------------------+         Tick Clock (Fixed 50ms)        +---------------------+
| Simulation Host     | -------------------------------------> | Input Ring Buffer   |
+---------------------+                                        +---------------------+
           |                                                              |
           v                                                              v
+---------------------+         Strictly Deterministic         +---------------------+
| State Snapshot T_n  | -------------------------------------> | State Snapshot T_n+1|
| (Fixed-Point Math)  |         Execute Frame Step             | (Merkle State Hash) |
+---------------------+                                        +---------------------+
Enter fullscreen mode Exit fullscreen mode

Production Implementation: Fixed-Point Deterministic Engine

from __future__ import annotations

import hashlib
import struct
from dataclasses import dataclass, field
from typing import Any

FIXED_SHIFT = 16
FIXED_SCALE = 1 << FIXED_SHIFT  # 65536 multiplier for 16.16 fixed point


def float_to_fixed(val: float) -> int:
    return int(round(val * FIXED_SCALE))


def fixed_to_float(val: int) -> float:
    return float(val) / FIXED_SCALE


@dataclass
class EntityState:
    entity_id: int
    pos_x: int  # Fixed point
    pos_y: int
    vel_x: int
    vel_y: int

    def step(self) -> None:
        self.pos_x += self.vel_x
        self.pos_y += self.vel_y

    def serialize_binary(self) -> bytes:
        return struct.pack("!Iiiii", self.entity_id, self.pos_x, self.pos_y, self.vel_x, self.vel_y)


class DeterministicSimulation:
    def __init__(self, tick_rate_hz: int = 20):
        self.tick = 0
        self.tick_interval_ms = 1000 // tick_rate_hz
        self.entities: dict[int, EntityState] = {}

    def spawn_entity(self, entity_id: int, x: float, y: float, vx: float, vy: float) -> None:
        self.entities[entity_id] = EntityState(
            entity_id=entity_id,
            pos_x=float_to_fixed(x),
            pos_y=float_to_fixed(y),
            vel_x=float_to_fixed(vx),
            vel_y=float_to_fixed(vy),
        )

    def advance_tick(self) -> str:
        """Executes a single lockstep frame and returns the Merkle SHA256 state hash."""
        # Entities are sorted by entity_id to eliminate dict iteration non-determinism
        sorted_ids = sorted(self.entities.keys())
        hasher = hashlib.sha256()

        for eid in sorted_ids:
            ent = self.entities[eid]
            ent.step()
            hasher.update(ent.serialize_binary())

        self.tick += 1
        state_hash = hasher.hexdigest()
        return state_hash


def run_verification() -> None:
    sim1 = DeterministicSimulation()
    sim2 = DeterministicSimulation()

    for sim in (sim1, sim2):
        sim.spawn_entity(101, x=10.5, y=20.0, vx=1.2, vy=-0.5)
        sim.spawn_entity(102, x=-5.0, y=100.25, vx=0.0, vy=2.1)

    print("Executing 100 deterministic lockstep ticks...")
    for _ in range(100):
        h1 = sim1.advance_tick()
        h2 = sim2.advance_tick()
        assert h1 == h2, f"Desynchronization detected at tick {sim1.tick}!"

    print(f"Lockstep verified! Final Tick: {sim1.tick} | State Hash: {h1[:16]}...")


if __name__ == "__main__":
    run_verification()
Enter fullscreen mode Exit fullscreen mode

Production Takeaways

  1. Sort Keys for Traversal: Never iterate unordered Python hash tables without sorting keys first; iteration order can vary across runs.
  2. Fixed-Point Quantization: Shift real-world values into integer scale (16.16 or 32.32) to prevent cross-platform floating-point drift.
  3. Checksum Verification: Compute state hashes every N ticks to detect desyncs immediately in networked simulations.

GitHub Repository: github.com/aman179102

Top comments (0)