Skip to content

GNode.hashCode: spread nodes with MurmurHash3's finalizer, and add a switch for run-independent hashes - #373

Open
royalbert wants to merge 1 commit into
joernio:masterfrom
royalbert:gnode-hashcode-deterministic
Open

royalbert wants to merge 1 commit into
joernio:masterfrom
royalbert:gnode-hashcode-deterministic

Conversation

@royalbert

@royalbert royalbert commented Nov 17, 2026 •

Copy link
Copy Markdown

GNode.hashCode is Objects.hash(graph, nodeKind, _seqId), since #127. This PR has one commit, which replaces it with MurmurHash3's 64-bit finalizer (fmix64) applied to the node's id() with the graph's identity hash in the upper half, folded to 32 bits, and adds a switch, GNode.mixInGraphIdentity, that leaves the identity hash out.

  • Nodes collide. Within one graph, the current hash is 31 * nodeKind + seq plus a constant, so kind k at seq s + 31 has the same hash as kind k + 1 at seq s, and the nodes of every kind fall into the range of the largest kind. In a coreboot graph of 9,680,014 nodes, 8,661,826 (89.5%) share their hash with another node, up to 28 on one value. With the new hash and the switch off, 21,689 do, at most 3 on one value. With it on, the count depends on the graph's identity hash: for five random values in its place, on the 9,680,012 nodes of the benchmark below, 21,592 to 21,869, at most 4. A random 32-bit hash gives about 21,800.
  • The switch. With mixInGraphIdentity on, the default, the hash mixes in the graph's identity hash, as 0.1.36 does, so hash-based collections of nodes iterate in a different order in every run. With it off, a node's hash depends only on its kind and seq, so two builds of the same graph give every node the same hash. It is turned off with the system property flatgraph.GNode.mixInGraphIdentity=false or with AccessHelpers.setMixInGraphIdentity(false), before any node is hashed.

Why the switch

Code should not depend on the iteration order of a hash map. With the switch on, code that does gives different results from run to run, so tests can catch it. Off is for users who need the same graph from every build of the same code, for example to show that no code has changed between two builds, or that a change meant to leave the output alone does. Whether the default should change is a separate discussion.

Joern's passes build edges while iterating such collections, for example CdgPass through CfgDominatorFrontier's mutable.Map and mutable.Set of nodes, and the reaching-definitions pass. Eleven C and C++ code bases, each built the same way several times with Joern master 011ed31bf (the builds of the Performance section below: 6 per version or switch setting for the seven smaller code bases, 2 for the four larger):

  • With flatgraph-core 0.1.36, and with this change with the switch on, no two builds of a code base give the same graph file. Builds 1 and 2 with 0.1.36, compared node by node, have the same nodes, properties and edges, but the CDG and REACHING_DEF edges are stored in a different order at the nodes counted below.
  • With the switch off, every build of a code base gives the same graph file, byte for byte.
code base nodes 0.1.36: nodes whose edge order differs
Intel TDX loader 49,627 6,309
ESnet SmartNIC firmware 123,609 12,063
MCUboot 86,339 15,416
OpenPOWER OCC 337,491 51,217
Sound Open Firmware 721,341 96,825
NXP i.MX System Manager 463,938 49,129
OpenThread 369,652 68,475
OP-TEE OS 2,324,060 441,899
Chromium EC 2,163,898 272,900
coreboot 9,680,014 966,850
U-Boot 11,033,886 1,494,849

Cause

Graph has no hashCode of its own, so Objects.hash(graph, …) uses the graph object's identity hash, which the JVM assigns afresh in every run. #127 first paired this hashCode with an equals on (graph, nodeKind, seq); review kept equality by identity and removed the equals, and the hashCode kept the graph. Objects.hash combines its arguments linearly (multiply by 31, add the next), so kind and seq only shift the hash, and nodes of different kinds land on the same values.

Change

core/src/main/java/flatgraph/GNode.java (the now unused java.util.Objects import is removed):

+    /** Whether `hashCode` mixes in the graph's identity hash. With it on, hash-based collections of nodes iterate in a
+     * different order in every run; with it off, a node hashes the same in every run. On unless the system property
+     * `flatgraph.GNode.mixInGraphIdentity` is `false`. Change it through `AccessHelpers` only before any node is hashed:
+     * a node in a hash-based collection is not found after a change. */
+    static boolean mixInGraphIdentity = !"false".equals(System.getProperty("flatgraph.GNode.mixInGraphIdentity"));
+
+    /** MurmurHash3's 64-bit finalizer applied to `id()`, with the graph's identity hash in the upper half if
+     * `mixInGraphIdentity` is on and the node has a graph, folded to 32 bits. It spreads the nodes of all kinds over
+     * the whole int range. Equality is by identity.
+     * The finalizer is fmix64 in https://github.com/aappleby/smhasher/blob/07bb4de10a63e8cc2e1724865454eba635742383/src/MurmurHash3.cpp#L81-L90 */
     @Override
     public int hashCode() {
-        return Objects.hash(graph, nodeKind, _seqId);
+        long h = id();
+        if (mixInGraphIdentity && graph != null) h ^= (long) graph.identityHash() << 32;
+        h ^= h >>> 33;
+        h *= 0xff51afd7ed558ccdL;
+        h ^= h >>> 33;
+        h *= 0xc4ceb9fe1a85ec53L;
+        h ^= h >>> 33;
+        return (int) (h ^ (h >>> 32));
     }

core/src/main/scala/flatgraph/Graph.scala:

+  private var _identityHash: Int = 0
+
+  /** The graph's identity hash, which `GNode.hashCode` mixes in when `GNode.mixInGraphIdentity` is on. It is taken the first time it is
+    * needed and kept, so only the first node hashed calls `System.identityHashCode`. 0 means not yet taken (HotSpot never gives 0 as an
+    * identity hash); threads that take it at the same time store the same value.
+    */
+  private[flatgraph] def identityHash: Int = {
+    var h = _identityHash
+    if (h == 0) {
+      h = System.identityHashCode(this)
+      _identityHash = h
+    }
+    h
+  }

core/src/main/java/flatgraph/AccessHelpers.java gets getMixInGraphIdentity() and setMixInGraphIdentity(boolean).

  • Equality is unchanged: GNode does not override equals, so equal nodes are the same object and have the same hash.
  • The identity hash is taken the first time a node of the graph is hashed and kept in the Graph. Calling System.identityHashCode(graph) in every hashCode made the random-order lookups below about 45% slower than with the switch off; kept, it costs about 11%, the same as a value stored when the graph is created. Taking it in the Graph constructor instead gave the same value in every build: six builds of the same code gave six identical graph files. HotSpot draws identity hashes from a per-thread pseudo-random sequence, so a value taken at the same point of the same thread repeats from run to run. Taken at the first hash, it is the value 0.1.36's Objects.hash(graph, …) mixes in.

Performance

A mutable.HashSet of objects with the node kinds and counts of a coreboot graph (9,680,012 nodes) and identity equality, JDK 21 on an arm64 laptop. Each figure is the median of 7 repetitions; a range covers two separate runs. Random order is a fixed shuffle; id order is ascending id(), that is by kind, then by seq.

operation flatgraph-core 0.1.36 this change, switch on this change, switch off
look up every node, random order 2,761–2,784 ms 380–382 ms 335–350 ms
add every node, id order 207–209 ms 772–773 ms 739–752 ms
look up every node, id order 144–145 ms 188–212 ms 154–156 ms

In id order, the current hash puts consecutive nodes in consecutive slots of the set; the new hash spreads them out.

Share of Joern's build CPU spent in GNode.hashCode, in the eleven code bases, on an arm64 Linux machine with JDK 21. Java Flight Recorder sampled every 1 ms. The figure is the share of the samples of the joern-parse process, which runs Joern's passes, that are in GNode.hashCode or the hashing it calls, pooled over the builds, with a 95% Wilson interval. The C/C++ frontend runs in a process of its own and hashes no nodes. The 0.1.36 builds alternated with builds of an earlier version of this change; the builds with the switch on and off alternated with each other.

code base methods flatgraph-core 0.1.36 this change, switch on this change, switch off
Intel TDX loader 1,677 4.69% [3.93–5.58] 0.00% [0.00–0.14] 0.12% [0.04–0.34]
ESnet SmartNIC firmware 2,107 3.46% [2.95–4.07] 0.15% [0.07–0.31] 0.02% [0.00–0.13]
MCUboot 2,283 4.63% [3.96–5.40] 0.12% [0.05–0.30] 0.00% [0.00–0.11]
OpenPOWER OCC 4,856 3.95% [3.59–4.34] 0.10% [0.06–0.18] 0.05% [0.02–0.12]
Sound Open Firmware 10,804 0.33% [0.31–0.34] 0.017% [0.014–0.021] 0.013% [0.011–0.017]
NXP i.MX System Manager 11,311 3.37% [3.06–3.71] 0.15% [0.10–0.24] 0.12% [0.07–0.20]
OpenThread 14,128 2.57% [2.28–2.89] 0.07% [0.03–0.14] 0.02% [0.01–0.07]
OP-TEE OS 24,408 3.49% [3.31–3.68] 0.10% [0.08–0.14] 0.09% [0.06–0.12]
Chromium EC 55,698 4.20% [3.95–4.47] 0.17% [0.12–0.23] 0.08% [0.05–0.13]
coreboot 88,121 3.83% [3.70–3.96] 0.17% [0.15–0.20] 0.14% [0.12–0.17]
U-Boot 137,885 1.00% [0.97–1.03] 0.04% [0.04–0.05] 0.04% [0.03–0.05]
  • With 0.1.36 the share is 2.6–4.7% in nine of the eleven, and 0.3% and 1.0% in Sound Open Firmware and U-Boot, whose passes take the most CPU. The lowest single build with 0.1.36 is at 0.30%.
  • With this change it is 0.00–0.17% with the switch on and 0.00–0.14% with it off.
  • The figure is the cost of computing the hash, which in Objects.hash means allocating an array and boxing two of the arguments. It does not include time that hash collections spend walking past colliding entries.
  • All versions give the same methods and calls in every code base.

Testing

  • New GraphTests case: with the switch on, 200 nodes of two kinds have 200 different hashes, and two graphs built the same way have different hashes; with it off, they have the same hashes and a HashSet of each graph's nodes iterates in the same order; in both, a node of one graph is not equal to the node with the same kind and seq in the other. It fails if hashCode ignores the switch either way.
  • sbt scalafmtCheck Test/scalafmtCheck test passes: 219 succeeded, 0 failed (master: 218).
  • Joern master 011ed31bf with flatgraph-core 0.1.36 plus this change, on macOS (arm64): testFull passes in every module (8,442 succeeded, 0 failed, with Rust 1.99.1 for rust2cpg), c2cpg/stage ; integrationTests/testFull passes (15 succeeded, 0 failed), and testDistro.py passes every stage in 2 of 2 runs.
  • Joern picks this up once it depends on a flatgraph release that includes it.

@bbrehm bbrehm left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent performance improvement. 👍, good catch, embarassing for me.

Our general coding guideline wrt hashmap iteration order stability across joern and the commercial extension (codescience) is:

We have had really bad bugs caused by non-reproducibility in hashmap iteration order. So never assume that hashmap iteration order is reproducible; tend to use LinkedHashMap or various normalization schemes. I think we even have custom linter rules to help us stick to that.

This change improves the reproducibility for unordered hashmaps of GNode specifically, but not for unordered hashmaps of other objects.

But "look into the hashCode implementation, check whether it ever touches the effectively randomized identity-hash" is maybe not a sustainable coding guideline. If this change ends up promising "hashCode for GNode is deterministic/reproducible", then reviewing code for reproducibility/determinism bugs becomes much harder (no more bright red line in the sand), and we will cry on every scala stdlib update (I think unordered hashmap iteration order is not promised stable on bugfix/point releases).

If this change instead ends up as "keep bright red line, but mitigate the impact for unordered maps of GNode", then we mask bugs: Testing will never see the issue until we e.g. try to update our scala version.

I propose to split this update:

  1. Better hashCode: Add a static boolean mixInGraphIdentity = true; and mix the graph's identity in if that is true (predictable branch is approximately free), using murmur/fmix; don't forget to make that safe if the graph is null (ugly ugly legacy hacks in the commercial extension that you can't see). Also add public getter/setter in AccessHelpers.java . I will insta-approve that, awesome change without all the trade-offs, and your projects downstream of flatgraph can simply decide to make that stable, using the public setter.
  2. Second PR: Have a serious design discussion. Do we want to promise hashCode determinism to joern+codescience? Do we want the hashCode coincidentially stable (default mixInGraphIdentity = false; use the public getter/setter to enable randomization/mix-in for some tests)? For that, I will invite a bunch of people to the second PR discussion+review.

…switch for run-independent hashes

Hash a node with MurmurHash3's 64-bit finalizer of its id (kind and seq), with the graph's identity
hash in the upper half, folded to 32 bits. The current hash, Objects.hash(graph, nodeKind, _seqId), is
linear in kind and seq, so nodes of different kinds share hash values (89.5% of a coreboot graph's
9,680,014 nodes; about 0.2% with the new hash).

GNode.mixInGraphIdentity, on by default, mixes in the graph's identity hash, so hash-based collections
of nodes iterate in a different order in every run, as before. The graph takes its identity hash the
first time a node is hashed and keeps it. With the switch off (system property
flatgraph.GNode.mixInGraphIdentity=false, or AccessHelpers.setMixInGraphIdentity), a node hashes the
same in every run, and two builds of the same code give byte-identical graphs.
@royalbert royalbert changed the title GNode.hashCode: mix the node id, so hashes spread out and are the same in every run GNode.hashCode: spread nodes with MurmurHash3's finalizer, and add a switch for run-independent hashes Nov 18, 2026
@royalbert
royalbert force-pushed the gnode-hashcode-deterministic branch from db9712e to 64f627e Compare November 18, 2026 03:42
@royalbert

royalbert commented Nov 18, 2026 •

Copy link
Copy Markdown
Author

Thanks, I really like the solution of creating a property to enable/disable the deterministic hash algorithm.

I have been doing a lot of work on optimizing algorithms in Joern in order to deal with much larger methods and repos. Being able to turn on the deterministic hash algorithm makes it easier for both me and others to validate that the new algorithms are building the exact same graph (down to the order of its edges).

The PR now does this: GNode.mixInGraphIdentity, on by default, with accessors in AccessHelpers and a system property to turn it off. Ready for another look.

@royalbert
royalbert requested a review from bbrehm November 19, 2026 03:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants