Skip to content

engine: hash every identifier-keyed map one way - #1089

Closed
bpowers wants to merge 1 commit into
mainfrom
ident-map-one-hasher
Closed

bpowers wants to merge 1 commit into
mainfrom
ident-map-one-hasher

Conversation

@bpowers

@bpowers bpowers commented Oct 12, 2026

Copy link
Copy Markdown
Owner

Fixes #317

What this does

Every map or set keyed by an interned identifier is now IdentMap / IdentSet, over one hasher type.
Before, about 190 were on std's SipHash, about 40 on the FxHash IdentMap alias, and about 20 on FxHashMap spelled directly.
scripts/lint-project.sh refuses the other spellings wherever the key type is written down.

It also answers the issue's design question: keep the content hash; do not move to pointer, id or salsa::interned hashing.
The reasoning and numbers are below, and are written down as a standing constraint in the rustdoc on CanonicalStorage and in docs/design/engine-performance.md ("Identifier hashing").

Measurements

Callgrind, exact instruction counts, one cold compile (examples/clearn_profile.rs, --toggle-collect on its compile function, release + debuginfo, mimalloc).
Costs are summed by source file, so hashing that was inlined into a caller is still counted; scripts/callgrind-by-file.py --idents (new, checked in) prints these rows.

main a8f3da45 this PR change
WORLD3 compile, instructions 53,949,423 52,498,643 -2.7%
SipHash 4,613,264 (8.55%) 3,278,374 (6.24%) -29%
FxHash 655,333 (1.21%) 705,787 (1.34%)
interner 1,341,532 (2.49%) 1,341,739 (2.56%)
refcounts of every Arc 199,789 (0.37%) 198,197 (0.38%)
C-LEARN compile, instructions 873,795,124 847,270,288 -3.0%
SipHash 68,176,812 (7.80%) 49,315,704 (5.82%) -28%
FxHash 18,621,926 (2.13%) 19,675,311 (2.32%)
interner 23,905,782 (2.74%) 24,134,395 (2.85%)
refcounts of every Arc 3,300,517 (0.38%) 3,281,422 (0.39%)

Whole-process retired instructions (scripts/perf-ab.py --perf, 5 interleaved rounds, parse and one run included): C-LEARN -2.3%, WORLD3 -2.7%, WORLD3 with LTM -2.8%; the same binary against itself read +0.05%.
These were taken one commit before the final tree (no release-build code changed after), and the callgrind table above is from the final tree.
Wall clock moved the same direction (-2.4% on C-LEARN compile) but the null control read -0.5% on a loaded machine, so I am not claiming a wall-clock number.

Against the issue's original baseline (WORLD3 project_build: 16.6M SipHash + 2.3M String::clone of 212.4M): that stage no longer exists, and the whole WORLD3 compile is now a quarter of what project_build alone was.
In absolute instructions, hashing plus cloning went from 18.9M to about 4.2M (SipHash 3.28M + FxHash 0.71M + all refcounts 0.20M), so the ">50% less" target is met, mostly by work that landed before this PR.
As a share of the compile, hashing is still about 7.6%, and most of that is SipHash on maps this PR does not touch (see "What is left").

The design decision

Today an identifier is a handle: equal by pointer, cloned by a refcount bump, but hashed by walking its string.
The original proposal was to make the hash an integer too.
I recommend against it, for good, because the prize is small and each way of getting it breaks something the engine relies on.

The prize. On C-LEARN, all FxHash is 2.32% of the compile. Of that:

share of compile
the compiler's String-keyed name table 0.81%
the interner hashing a string it was asked to intern 0.48%
&str-keyed maps and &str probes of identifier maps 0.55%
everything else: an upper bound on lookups by a handle 0.45%

An integer hash can only help the last row.
A Copy id instead of a refcounted handle could save at most the 0.39% that all Arc refcounts cost.

What it would cost.

  • &str lookups. map.get("population") works on an identifier-keyed map because the handle hashes exactly as its string does.
    That is what Borrow<str> promises, and std cannot check it: hash the handle any other way and every such lookup silently misses.
    Thirty production call sites do this (I removed the three Borrow<str> impls and counted the compile errors).
    They are the lookups where the caller has text and no handle: one segment of a module·var path, an element name in a subscript, a name from a host.
    With an integer hash each would have to intern first, which is the same string hash plus a lock and a refcount round trip.
    So the larger share (0.55%) gets slower to make the smaller share (0.45%) faster.
  • Deterministic order. A pointer differs run to run; an interning-order id differs with what the process compiled earlier. Map order would follow.
  • Identifiers without a database. A salsa::interned id can only be read through its database.
    Fifty of the eighty engine files that use identifiers never see one, about ninety BTreeMap/BTreeSet types sort identifiers by string, and compiled simulations, results and diagnostics carry identifiers out to hosts and across databases.
    Salsa also reclaims and reuses interned ids, which is why the engine already forbids holding one in a memoized value.

If handle-keyed lookups ever do show up in a profile, the design that keeps all three properties is a content hash stored in the interned payload plus a &str probe type. That is written down too. I would not build it now.

Two things I did that you did not ask for

1. The hasher is random in debug builds.
IdentBuildHasher is FxHash in release and std's randomly keyed SipHash when debug assertions are on (tests, the gates profile).
The determinism suites catch "a map's iteration order reached a cached value" by building twice and comparing, which only works if the order differs between builds.
With everything on FxHash it does not: I deleted the sort in Compiler::new and multi_table_fragment_is_stable_across_fresh_databases still passed.
So plain standardization would have quietly disarmed those tests for about 190 more maps (the ~60 already on FxHash were already disarmed).
With the random key back, the same mutation fails on the first repeat.
Release builds are unaffected, and keep an order that cannot vary run to run.
Cost: engine test CPU is 122.8 s against 120.1 s with FxHash forced in debug (four cores, median of 3), so at most +2.2%.
If you would rather have one hasher in every build, it is a small change in common.rs, but the determinism tests then stop constraining identifier maps.

2. Two order leaks, found and fixed.

  • Re-arming the tests immediately made a_cycle_written_beside_one_the_model_had_is_refused flaky.
    The dependency walk visited variables in the variable map's hash order, so which of a model's cycles got reported was hash order (FxHash had been hiding it).
    It now walks in name order.
    One corpus model changes its message: RealBeer4-Sterman13.mdl reports the minimum_inventory self-cycle instead of the peak_inventory one.
  • simulate --ltm in the CLI listed models' loops in the model map's order, which differs run to run on main. It now lists in name order.

What is left (your call)

SipHash is still 5.8% of a C-LEARN compile, on maps not keyed by identifier types:

share
names held as String: VariableLayout (probed per VarRef by resolve_var_ref), the sync state, the fragment maps, expand_maps_to_chains ~3.0%
graphical-function dedup by content (FragmentMerger::absorb) 1.3%
small integer keys (literal interning, constant info) 0.4%

The first row is the real next step on this issue's axis, and I left it out because it is a re-keying, not a respelling.
The right fix is to key those maps by the Ident they already name, so the lint covers them and handle lookups compare pointers.
That touches the salsa input schema (SourceProject.models, SourceModel.variables are HashMap<String, _>) and the layout.
I would expect roughly 2% of compile instructions from it, and would do it as its own PR.
The other two rows are a one-line hasher change each, but they are not identifier maps and the GF one hashes model data, so I did not fold them in.

Evidence

  • Standardization is complete, including inferred types. The lint only sees written types, so I also listed every hashbrown::HashMap<K, V, RandomState> instantiation in the debug test binaries (nm -C; nothing is inlined in debug) and checked none has an identifier key. That found a handful the grep could not (maps keyed through the ModuleKey alias, three with inferred types). The only one left is a deliberate test.
  • Tests added: common::interned_identifier_tests::ident_maps_and_sets_are_probed_by_handle_and_by_str (a row per identifier type), every_identifier_type_hashes_as_its_str (under SipHash, FxHash and IdentBuildHasher), ident_map_order_is_random_per_map_exactly_under_debug_assertions, db::diagnostic_determinism_tests::the_cycle_reported_among_several_is_a_function_of_the_model, and simlin-cli's ltm_loop_report_lists_models_in_name_order. The last two failed before their fixes.
  • Lint: fails on main with about 237 hits; a planted violation in each spelling (multi-line, reference with lifetime, Fx) is caught.
  • Compiled artifact unchanged: the clearn_profile bytecode profile (opcode counts, tables, slots) is identical for C-LEARN and for WORLD3 with LTM.
  • Corpus sweep: base and tree simlin simulate over all 509 models under test/, plain and --ltm (1018 runs). stdout is identical in every run. stderr differs only for the RealBeer4 cycle message above and for the --ltm loop listing, which main prints in a different order from run to run (main against itself differs on 7 runs; this tree against itself on 0).
  • Flakiness: with the random key and after the cycle fix, the engine suite ran 27 times and the whole workspace suite 4 times (plus three pre-commit hook runs) with no failure. scripts/gates.sh passes (it runs with debug assertions, so under the random key).

What this does not establish

  • No wall-clock claim; instructions only.
  • The 0.45% ceiling is an upper bound from attribution by enclosing function, not a measurement of a prototype. I did not build an integer-hash prototype.
  • The lint cannot see a map whose key type is inferred and never meets an IdentMap signature. The nm scan says there are none today; nothing but review keeps it so.
  • Random keys make an order leak likely to fail a repeated-build test, not certain to. About thirty clean runs is evidence, not proof, that no other leak exists.
  • The release-profile test suite is never run, so ident_map_order_is_random_per_map_exactly_under_debug_assertions only ever exercises its debug arm.
  • The wasm bundle and pysimlin were built and tested by the pre-commit hook, but I did not measure compile time there.

Maps keyed by an interned identifier were spelled three ways: about 190
on std's SipHash, about 40 on the FxHash IdentMap alias and about 20 on
FxHashMap directly. They are now all IdentMap or IdentSet, over one
hasher type, IdentBuildHasher, and scripts/lint-project.sh refuses the
other spellings wherever the key type is written down. A cold compile
retires 3.0% fewer instructions on C-LEARN and 2.7% fewer on
WORLD3 (callgrind), all of it SipHash that is no longer run.

IdentBuildHasher is FxHash in a release build and std's randomly keyed
SipHash in a build with debug assertions. The determinism suites detect
a map's iteration order reaching a cached value by building twice and
comparing, which needs the order to differ between builds; on an
unkeyed hasher multi_table_fragment_is_stable_across_fresh_databases
passes with the sort it pins deleted. Keeping the random key where the tests run found one such leak
at once: the dependency walk visited variables in the variable map's
order, so which of a model's cycles was reported was hash order. It now
walks in name order.

The differential sweep of the CLI over the corpus found a second, in
the CLI itself: simulate --ltm listed models' loops in the model map's
order, which differed run to run. It lists them in name order.

The identifiers keep hashing as their strings. A pointer or interned-id
hash would save at most 0.45% of a C-LEARN compile and would break the
thirty call sites that probe a map with a &str, make map order depend on
allocation, or tie identifiers to a database; the rustdoc on
CanonicalStorage and docs/design/engine-performance.md record the
measurement and the constraint. scripts/callgrind-by-file.py is the
tool the shares were measured with.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-12T06:18:38.016646Z 292a330 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@claude

claude Bot commented Oct 12, 2026

Copy link
Copy Markdown

Review summary

Reviewed the hasher standardization, the IdentBuildHasher implementation, the lint rule, the two order-leak fixes, and the test additions.

The design is sound and the implementation is correct:

  • IdentBuildHasher preserves the Borrow<str> contract for the three interned identifier types in both debug and release configurations.
  • Each IdentBuildHasher::default() call creates a fresh RandomState under debug_assertions, giving every map its own random key as the determinism suites require.
  • The behavioral changes in model_dependency_graph_impl (walking 0..n in dense-index/name order instead of var_info.keys()) and ltm_loop_report (sorting models by name) are explicit, intentional fixes and each is covered by a new test (the_cycle_reported_among_several_is_a_function_of_the_model, ltm_loop_report_lists_models_in_name_order) that would have failed before the fix.
  • The lint pattern catches every realistic spelling of a (Fx)?Hash(Map|Set) keyed by an identifier type or key built from one.
  • The reclassification of maps keyed by non-identifier types (e.g. IdentMap<usize, Vec<&str>> in dep_graph.rs) under the same alias is intentional per the design doc, so the rustc_hash types are named in common.rs and nowhere else in the compiler.

No findings.

Overall correctness verdict: correct.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 292a330fa7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/lint-project.sh
# types and the engine's keys built from them. It sees only a type that is
# written down: a map whose key type is inferred is caught where it meets an
# IdentMap in a signature (the hasher is part of the type), or not at all.
IDENT_KEYED_PATTERN='\b(Fx)?Hash(Map|Set)<\s*\(?\s*&?\s*('"'"'\w+\s+)?((crate::|simlin_engine::)?common::)?(Ident|CanonicalElementName|CanonicalDimensionName|VarRef|ModuleKey|ModuleEdgeKey)\b'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recognize qualified composite key types in the lint

The optional path portion only matches crate::common:: or simlin_engine::common::, so declarations such as HashMap<crate::compiler::VarRef, _>, HashSet<crate::vm::ModuleKey>, or their fully qualified equivalents pass this new check even though these are explicitly listed as identifier-derived keys. This leaves a common Rust spelling outside the ratchet and allows the alternate hashers the lint is intended to prevent; accept arbitrary module prefixes, or enumerate the actual modules for these composite key types.

Useful? React with 👍 / 👎.

@bpowers

bpowers commented Oct 12, 2026

Copy link
Copy Markdown
Owner Author

Landed on main as 78b0409 (squash); GitHub did not mark the PR merged, so closing by hand.

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.

engine: decide whether identifier interning closes the compile-cost issue

1 participant