Repository navigation
Conversation
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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Review summaryReviewed the hasher standardization, the The design is sound and the implementation is correct:
No findings. Overall correctness verdict: correct. |
There was a problem hiding this comment.
💡 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".
| # 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' |
There was a problem hiding this comment.
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 👍 / 👎.
|
Landed on main as 78b0409 (squash); GitHub did not mark the PR merged, so closing by hand. |
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
IdentMapalias, and about 20 onFxHashMapspelled directly.scripts/lint-project.shrefuses 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::internedhashing.The reasoning and numbers are below, and are written down as a standing constraint in the rustdoc on
CanonicalStorageand indocs/design/engine-performance.md("Identifier hashing").Measurements
Callgrind, exact instruction counts, one cold compile (
examples/clearn_profile.rs,--toggle-collecton 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.a8f3da45ArcArcWhole-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.3MString::cloneof 212.4M): that stage no longer exists, and the whole WORLD3 compile is now a quarter of whatproject_buildalone 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:
String-keyed name table&str-keyed maps and&strprobes of identifier mapsAn integer hash can only help the last row.
A
Copyid instead of a refcounted handle could save at most the 0.39% that allArcrefcounts cost.What it would cost.
&strlookups.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·varpath, 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.
salsa::internedid can only be read through its database.Fifty of the eighty engine files that use identifiers never see one, about ninety
BTreeMap/BTreeSettypes 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
&strprobe 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.
IdentBuildHasheris FxHash in release and std's randomly keyed SipHash when debug assertions are on (tests, thegatesprofile).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::newandmulti_table_fragment_is_stable_across_fresh_databasesstill 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.
a_cycle_written_beside_one_the_model_had_is_refusedflaky.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.mdlreports theminimum_inventoryself-cycle instead of thepeak_inventoryone.simulate --ltmin 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:
String:VariableLayout(probed perVarRefbyresolve_var_ref), the sync state, the fragment maps,expand_maps_to_chainsFragmentMerger::absorb)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
Identthey already name, so the lint covers them and handle lookups compare pointers.That touches the salsa input schema (
SourceProject.models,SourceModel.variablesareHashMap<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
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 theModuleKeyalias, three with inferred types). The only one left is a deliberate test.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 andIdentBuildHasher),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'sltm_loop_report_lists_models_in_name_order. The last two failed before their fixes.Fx) is caught.clearn_profilebytecode profile (opcode counts, tables, slots) is identical for C-LEARN and for WORLD3 with LTM.simlin simulateover all 509 models undertest/, plain and--ltm(1018 runs). stdout is identical in every run. stderr differs only for theRealBeer4cycle message above and for the--ltmloop 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).scripts/gates.shpasses (it runs with debug assertions, so under the random key).What this does not establish
IdentMapsignature. Thenmscan says there are none today; nothing but review keeps it so.ident_map_order_is_random_per_map_exactly_under_debug_assertionsonly ever exercises its debug arm.