Proposal: an opt-in emulator flag that makes map order independent of atom creation order

I’ve been working on making our Elixir application build reproducibly under Bazel. After enabling deterministic, fixing the build path and normalising timestamps, we still had a bunch of BEAM files that differed between builds of identical sources.

This matters to us because we share cached build results between developers and CI. When a compilation has to run again, we want unchanged inputs to produce unchanged output. A dependency producing a slightly different BEAM file can invalidate our Dialyzer PLT and the builds downstream of it, even though nothing meaningful has changed.

The common cause was code iterating maps whose keys contained atoms.

For small maps, atom keys are ordered by their atom-table indices. For large maps, the internal hash uses those indexes so iteration order depends on them too and atoms nested inside tuple or list keys can have the same effect.
It is race condition which process happens to create a giiven atom first.

Parallel compilation is one source of variation but also the boot loader loads modules in parallel, before any of our build code runs. I found that even just two bare VM starts can assign different indices to thousands of atoms!

We found this showing up in several fairly ordinary places.. like for example:

  • Postgrex.ErrorCode groups error codes into a map and then generates clauses from it.
  • Spark walks option maps while generating functions. Other modules had differences from struct defaults in debug information, maps escaped into literals, or a map being inspected into @doc.

None of these generators should rely on an unspecified iteration order. Sorting in the generator CAN fix this but getting a reproducible build this way means finding every relevant call site in every dependency, including places where the map traversal happens inside the compiler. it was a bit of a wack-a-mole situation and dependencies can break it with a new vesion. So we looked into fixing it at the source.

Previous Proof Earlier Wack-a-model fixes

I got the AI to look for previous reports of undeterminism in the map. There have already been fixes at several levels:

Reference What it addressed
OTP #5153 Large map literals could produce different BEAM files despite deterministic. Added deterministic encoding to term_to_binary/2 and made the compiler use it for literals.
Elixir #12350 Reported unstable exports_md5 values caused by encoding large maps. Closed without merging because Elixir already avoided that particular problem through list-based struct metadata.
Elixir #12418 Added explicit sorting when expanding struct fields following the map-ordering change in OTP 26.
Elixir #13517 Sorted map fields when converting type descriptions to quoted syntax, making the representation deterministic and fixing a flaky test.
OTP #11748 → #11774 Atom creation order affected the compiler’s type analysis and generated code. The fix made traversal of exported functions use a consistent order.

There is also related work in public_key #11396. and a broader reproducible-builds issue, #4417, dates back to 2020.

What I tried

My first attempt was to generate a boot script that pre-interned the atoms used by the build in a fixed order. That helped, but it required a complete atom list as a build input. Both not practical and defeated the point of not compiling more than needed.

The prototype adds an opt-in emulator flag, +zdao true, for “deterministic atom order”. While i think this should be enabled under deterministic builds, I figured it would be easier to merge if it had its own flag initially. It defaults to false.

When enabled the internal hash uses the atom’s name hash rather than its table index, and small flat maps compare atom keys by term order rather than index order.

The prototype

There is a prototype based on OTP 29.1, roughly 160 lines across ten files. There is also a prebuilt Ubuntu 24.04 x86-64 release.

I’d appreciate a review of that assumption, particularly around other consumers of the internal hash and any remaining code that assumes flat-map atoms are in index order.

We are now running this fork and it has stabilized out bazel build setup for the Elixir app.

(Edited to remove AI slop)

3 Likes

Hi @anagrius. The merits of your proposal aside, the text style vibes of AI to the point of throwing me off - which I’m sure other people will also feel. I’m sorry if this is a false positive, it’s just very frustrating to get your attention flooded with LLM output these days.

2 Likes

I updated the text to have fewer AI slop details, and hopefully more clearly describe the issue and proposal. :+1:

2 Likes

Sounds like there would be a more straightforward way to generate consistent cache keys for your builds, most people use a hash of the mix files.

This is one reason why people sometimes states that compilers can be non-deterministic. Since the CPU is non-deterministic due to speculative execution.

I never heard about any regulated field require this level of determination especially since we have a bigger hardware issue.

@Schultzer fair questions, thank you for the reply :slight_smile:

Hashing the Mix files is what we do for the compile step itself - - aand that part works well. The trouble is downstream in the build system. In Bazel (and Nix or similar tools) the outputs of one action are the inputs of the next build action , so the content hash of each BEAM file feeds the cache key of the dependents that compile against it, for example the Dialyzer PLT and the release artifacts. It is not something we can or would want to control ourselves.

If a dependency gets recompiled on a cold CI runner and its BEAM bytes come out different even though the sources did not change, everything after it is rebuilt too. A warm dependency cache hides this nicely until the day it is cold, which is exactly when you want the hits. In big monorepos like ours it can become make a huge difference in CI work + time.

Regarding speculative execution, I think we agree more than it sounds. SE changes timing, but the not results, so two runs may schedule differently but the instructions still produces same value. When compiler output depends on which process happened to intern an atom first, that is an ordinary race in software, and OTP seeems to already treats this class of thing as a bug:

that is what +deterministic, the deterministic term_to_binary encoding in #5153 and the ordering fix in #11774 I listed above fixed. This proposal is the same idea one level down instead of wack-a-mole solving each instance.

I never heard about any regulated field require this level of determination especially since we have a bigger hardware issue.

There is no regulatory motive on our side. We just want small changes to reuse as much compiled work as possible, and two builds of the same exact same source to be verifiably the exact same output artifact

1 Like

erts: Fix exact small map compare by garazdawi · Pull Request #11568 · erlang/otp · GitHub might this (still pending) PR solve your problem?

4 Likes

thanks for the pointer! That patch fixes comparisons of smal maps when they’re used as keys, affecting ordered iteration and deterministic encoding. The issue I’m seeing also occurs in ordinary map iteration, where atom creation order still affects traversal order. Code generators using that traversal can still produce different BEAM files between builds.

So I guess I should just make a PR at this point.

Or maybe comment at the existing PR first, see if they can fix that at the same time?

2 Likes

Yeah, since this PR originated in turn from `maps`: property tests by Maria-12648430 · Pull Request #11558 · erlang/otp · GitHub , the goal is clearly to have map iteration order deterministic in all cases.

2 Likes

Sorry @Maria-12648430 I am a bit swamp with stuff, but I will surely try to test your PR myself latest next week. I also wanted to learn property-based testing, which is why I need to find a bigger chunk of time. Thanks for your patience.

1 Like

No worries @kiko :upside_down_face:

1 Like

I made a PR but it got closed by @jhogberg closed it because he doesn’t want flags that change code behavior, and pointed out that compilers that aren’t deterministic when asked to be should be fixed instead. That makes sense for issues like the ones in the compilers themselves (like #11748 mentioned in my ooriginal post).

But what a compiler fix can’t fix is code that runs at compile time. Not sure I got that point across. A macro or parse transform that iterates a map to generate clauses or literals emits them in the map’s iteration order. That order depends on atom indices, so on the order atoms were created in that VM. With parallel boot and parallel compilation, that order varies between runs, so identical sources give different BEAM files.

So I jave tried to make a no-flag version: make map order independent of atom creation order for everyone.

This gives slower microbench results, but no differencen in actual compiles of real-world codebases is neglegeble:

Prototype (benchmarked on x86-64; the ARM JIT falls back to the C hash and is untested) erts: order and hash atom map keys by name hash (prototype) · berserkdb/otp@caa6d3f · GitHub

Results (EPYC 7502P, interleaved runs, median change vs stock OTP)

name hash ordering by name
Compile kernel, stdlib and compiler (90 s) +0.2% +0.3%
Elixir make compile (60 s) +0.9% +0.9%
maps:from_list, 8 to 32 atom keys +16 to +68% +20 to +527%
maps:merge, 16 + 16 keys +3 to +24% +40 to +272%
Dynamic-key lookup, 1000-key map +13 to +26% +34 to +49%
persistent_term:get +3 to +19% +50 to +70%
Literal-key match/update about ±12% about ±30%
Sort maps with differing keys +4 to +9% -70 to -78%

As you can see, ordering by name (what my original flag did) is far too slow for module-name keys, which just confirms the reasoning in #6151 (which has caused my pain). Ordering by name hash costs nothing measurable in whole compiles, but small-map construction is clearly slower in isolation. While the numbers here look high:

Compiling kernel, stdlib, the compiler iteself, and Elixir itself, shows no measurable difference (within ±1%).

In my mind this solves my repeatability issue and prevents future compiler bugs and the whole macro situation.

Questions

  1. Would ordering by name hash be acceptable unconditionally, given these costs? and if so what other benchmarks would you want to see (ARM64, specific workloads)? While it LOOKS like the cost is within noise on real world codebases, I would love a second opinion and benchmarks or more codebases.
  2. If the microbenchmark cost is too high to impose on everyone, does that change the view on an opt-in mode, used only by build VMs?

The prototype is at erts: order and hash atom map keys by name hash (prototype) · berserkdb/otp@caa6d3f · GitHub, and the benchmark harness, raw results and steps to reproduce are at otp/atom-order-bench at map-order-by-atom-name-hash · berserkdb/otp · GitHub.

First off, thank you for all of your contributions on making builds determinitic!

However, aren’t we just postponing the footgun with this change? Large maps still remain non deterministic, so once you cross the small → large map boundary, the same issue still appears, except now it is harder to detect.

For those reasons, I do think that trying to impose any ordering guarantee on maps is the wrong way to go about this. On the Elixir side, I’d rather try to find ways of making it clearer we are traversing a map during compilation, although how is not exactly clear at the moment.

Hey Jose, thanks for the the reply!

This is not just changing to small-map ordering, also works for large.

So, besides the flatmap order optimization for small maps, an atom’s internal hash becomes its name hash instead of its atom index, and that hash is what decides the hashmap layout. So large maps don’t depend on atom creation order either, and crossing the small to large boundary doesn’t bring the problem back.

I checked this with large maps of up to 150 keys that are atoms with all kinds of scenarios. Each comes out in the same order when the atoms are created in opposite orders on stock OTP every one of them differs.

You know much better if this is the right direction, I just have the very irritating issue that I cannot cache my builds :frowning:

So, I’d very much welcome a way to make compile-time map traversal visible on the Elixir side. Today we only find them by building twice and diffing BEAM files, which only catches cases where the order happened to differ.

My instinct just was that this was a more systemic issue that should be solved deeper down.

The tools that want to produce deterministic results from non-deterministic operations (map order) are buggy and should be fixed. All it takes is to sort at the affected places.

Redefining map order to be deterministic burdens the VM and the entire community for the benefit of what is by comparison a niche issue.

7 Likes

It seems to me that this fix does two things:

  1. Make the hash of atoms be deterministic (hash bytes of the atom rather than depend on intern order).
  2. Sort map contents.

It seems that making atom hashing deterministic builds would make sense as a runtime-level flag as this will aid stability, and maybe the parts that need sorted maps should be done in the relevant compilers?

At any rate, we’re running with @anagrius version in our build pipeline for now.

I’ve always wondered why this is something people want, not that there is anything wrong with, but given that you have absolutely no guarantee on how the CPU predicts stuff across architectures, then I don’t really get the benefit of all this determinism, although if it brings performance improvements then I’m game.