Quick note first: this is a real question I'm intersting in. I asked Claude to help me write it up so it comes out clearer, so please don't get mad 🙂 The measurements and the code are mine.
I'm making a small physics puzzle game for the browser: you place parts, press go, and a chain reaction either works or it doesn't. For puzzles, the same machine has to give the same result on every device. Otherwise a solution I check on my laptop might fail on someone's phone. So I tested it.
The test: the same 476 machine setups, run in Node (V8, Chrome's engine) and in jsc (JavaScriptCore, Safari's engine). Every half second of game time I hashed the exact position and angle of every body.
Result: 311 of 476 runs (65%) ended in a different state. No win/lose flipped in that sample, because the differences are tiny. But with enough players, a setup sitting right on a boundary will flip, and that's impossible to debug from a bug report.
The cause: in JavaScript, + - * / and Math.sqrt are exact by spec, so every engine gives the same bits. Math.sin, cos, atan2, acos, pow and hypot aren't, and engines round them differently. Matter.js calls five of them 18 times; my code added hypot.
The fix:
- Replacement versions of those six functions, built only from the exact operations. Sine, cosine and arctangent follow the old fdlibm routines. They're within about 1e-15 of the browser's own; the goal is to be the same everywhere, not more accurate.
- A pinned copy of Matter.js in the repo, with its calls pointed at those versions.
- A fixed 120 Hz step, no randomness or clock time in the simulation, and bodies always created in the same order.
After that, 476 of 476 runs matched bit for bit, and no result changed from the original.
To keep it from breaking:
- A check fails the build if the simulation calls one of the banned
Math functions. - One fingerprint hash of every level's run is compared in Node and in Safari's engine.
- A hidden page shows the same hash on any phone.
It matches so far on Android Chrome, desktop Chrome and desktop Safari. Firefox and iPhone aren't tested yet.
What I'd love to hear:
- Has anyone seen plain arithmetic differ between JS engines in real life? As far as I know, the spec doesn't allow fused multiply-add, but I'm curious about actual experience.
- If you went another way (Rapier's deterministic build, fixed-point, a Box2D port), was it worth it?
- Any devices or browsers known to break this kind of setup?
Thanks for reading, and thanks in advance for any experience you can share!