Repository navigation
fix: ensure JsValue equality and hashing consistency - #5702
raghavagarwal-debug wants to merge 5 commits into
Conversation
abdulhamid999
left a comment
There was a problem hiding this comment.
Audited core/engine/src/value/hash.rs, core/engine/src/value/equality.rs, and core/engine/src/builtins/number/mod.rs:
- Switching
RationalHashable::eqtoNumber::same_value_zeroand normalizingself.0 == 0.0to0.0_f64.to_bits()cleanly fixes theHash/Eqmismatch between-0.0,0.0, andJsVariant::Integer32(0). - One remaining edge case — non-canonical
NaNbit patterns:Number::same_value_zero(x, y)(builtins/number/mod.rs:906-912) returnstruefor any twoNaNvalues regardless of sign or payload bits (e.g.f64::NANvs-f64::NANorf64::from_bits(0x7ff8_0000_0000_0001)). Right nowRationalHashable::hashonly normalizes0.0, soself.0.to_bits()still produces distinct hashes for distinctNaNbit patterns that compare equal underRationalHashable::eq/JsValue::eq. Normalizingelse if self.0.is_nan() { f64::NAN.to_bits() }keeps theEq/Hashinvariant intact for allf64values as well.
|
@abdulhamid999 Thanks for pointing this out! I've updated the hash implementation to normalize NaN values as well as signed zero and added a regression test using different NaN bit patterns. I've verified both the default NaN-boxed representation and the jsvalue-enum configuration. Both targeted tests and the full boa_engine test suites pass. |
newmathphys
left a comment
There was a problem hiding this comment.
Reviewed the diff (and measured the semantics standalone with rustc, since a full boa_engine build is not available in my environment).
The change is correct, and the important part is the line that looks least exciting: switching RationalHashable::eq to Number::same_value_zero. Before it, the wrapper was internally consistent (it said +0.0 != -0.0 and hashed them differently) while JsValue::eq said they were equal — so the contract broke exactly at the JsValue boundary, which is the boundary users touch.
Measured before/after with the same helper functions and the same Hash bodies, no boa involved:
OLD ±0: eq=false hash_eq=false <- self-consistent wrapper, disagrees with JsValue
NEW ±0: eq=true hash_eq=true
OLD NaN payloads: eq=true hash_eq=false <- Eq claimed, hashes differed
NEW NaN payloads: eq=true hash_eq=true
OLD set.contains(-0.0)=false len=1
NEW set.contains(-0.0)=true len=1
Two small notes, neither blocking:
- The
is_nan()branch is currently redundant:tag_f64invalue/inner/nan_boxed.rsalready reduces any NaN tof64::NAN.to_bits()when the value is constructed, so a NaN with a foreign payload cannot reachHash. I would keep the branch (defence in depth) but add one line saying why — otherwise a reader concludes that payloads can reachHash, which contradicts the invariant the rest of the type relies on. - The regression tests cover
HashSet::contains(-0.0)andHashMap::get(-0.0)for floats, and hash equality forInteger32(0). AHashMaplookup with an integer key and a float probe (or the reverse) would pin the cross-variant case end-to-end, in the same style as the existing tests. Same for two distinct NaN payloads as one container key — you already assert equal hashes, so this is belt-and-braces rather than a gap.
No objection from me on the design: one canonicalisation shared by both sides is exactly what keeps them from drifting apart again. CI is the full check; I am happy to look again once it is green.
|
Short follow-up: the NaN normalisation you mention is already in the version I reviewed ( |
|
@newmathphys @abdulhamid999 Thanks for the detailed review and for independently verifying the behaviour! I've added an explanatory comment for NaN canonicalization and an additional HashMap regression test covering integer-zero keys with floating-point-zero lookups. I've pushed the updates to this PR and verified both the default and jsvalue-enum test configurations. I understand now. I'll add a comment explaining that NaN normalization here is defensive because tag_f64() already canonicalizes NaN values during construction. I'll also address the suggested cross-representation HashMap test. Thanks for the helpful suggestions! |
newmathphys
left a comment
There was a problem hiding this comment.
Both points are addressed, and I checked the claim about representations: jsvalue-enum is a real feature of the crate (core/engine/Cargo.toml:26), so confirming the tests under both layouts is exactly the right scope.
What I see in 7f05a3a / b39d996 / 4159f34:
- the NaN branch now says why it exists (canonicalisation happens at construction, this is belt-and-braces) — that removes the only misleading part of the patch;
integer_map.insert(JsValue::new(0), ...)probed withJsValue::new(0.0)closes the cross-variant case end-to-end, which was the test I could not do without a fullboa_enginebuild here;- signed zero and NaN payload tests are unchanged, still in the same style.
From my side this is good to merge once CI is green. Nothing further from me.
|
@newmathphys Thank you for the detailed review and for checking the updates! I appreciate your guidance throughout the review process. I'll keep an eye on the CI checks and wait for the remaining approvals. |
|
One practical note while you wait, so "stuck CI" is not misread: right now GitHub reports the PR as So there is nothing left for you to change from my review; it needs a maintainer approval (both for the workflow run and for the required review). A short ping in a day or two if it stays quiet is normal practice here. |
|
@newmathphys Thanks for clarifying! I'll wait a day or two for the maintainer approval and CI workflows to be addressed. Appreciate your guidance throughout the review! |
|
Hi @jedel1043 @HalidOdat @jasonwilliams , I wanted to kindly follow up on this PR. Could you please review the changes and let me know if any modifications are needed? If everything looks good, I'd really appreciate it if you could approve and merge the PR. Please also let me know if any action is required from my side regarding the pending workflow approvals. Thanks for your time and support! |
|
Independent verification of Mutation check (built locally at
|
| Build | State of hash.rs |
Result |
|---|---|---|
default (nan_boxed) |
as in the PR | PASS |
default (nan_boxed) |
whole fix reverted (same_value + raw to_bits) |
FAIL at tests.rs:126 — hash(+0.0) = 13646096770106105413 vs hash(-0.0) = 17224059632725561478 |
default (nan_boxed) |
only the NaN normalisation removed | PASS |
--features jsvalue-enum |
as in the PR | PASS |
--features jsvalue-enum |
only the NaN normalisation removed | FAIL |
So the -0.0 half of the test is a genuine regression test on the default build, and the NaN payload assertion only bites with the enum backend.
1. The NaN payload assertion is vacuous in the default build
JsValue::from(f64) stores through InnerValue::float64, and the default backend does not keep the payload:
// core/engine/src/value/inner/nan_boxed.rs
pub(super) const fn tag_f64(value: f64) -> u64 {
if value.is_nan() {
// Reduce any NAN to a canonical NAN representation.
f64::NAN.to_bits()
} else { value.to_bits() }
}So JsValue::new(f64::from_bits(0x7ff8_0000_0000_0001)) is already canonical NaN before it is ever hashed, and
let nan1 = JsValue::new(f64::NAN);
let nan2 = JsValue::new(f64::from_bits(0x7ff8_0000_0000_0001));
assert_eq!(hash_value(&nan1), hash_value(&nan2)); // passes with or without the fixcannot fail there. The legacy backend (--features jsvalue-enum) stores Float64(value) raw, so it does exercise the normalisation — that is the FAIL row above. Suggestion: either say so in a comment next to those two lines, or run this test with --features jsvalue-enum in CI so the branch is actually covered somewhere.
2. NaN values are canonicalized during construction is only true for one backend
The comment added in f64::NAN.to_bits() is accurate for nan_boxed and wrong for jsvalue-enum, where nothing canonicalises at construction. Since the whole point of that line is the enum backend, the current wording invites a future cleanup that deletes it as redundant. Worth rewording to something like: "the nan-boxed backend collapses NaNs at construction; the enum backend does not, so normalise here."
3. One assertion I would add (nonzero cross-variant)
The cross-variant case currently tested is new(0) vs new(-0.0) — zero, where both normalisations fire. JsValue::from(f64) -> Self::rational(value) does not fold integral floats into Integer32, so a nonzero pair is constructible and would lock the path that actually makes cross-variant hashing work:
let int_one = JsValue::new(1);
let float_one = JsValue::new(1.0);
assert_eq!(int_one, float_one);
assert_eq!(hash_value(&int_one), hash_value(&float_one));That works today only because the width is dropped on both sides:
JsVariant::Integer32(integer) => RationalHashable(f64::from(integer)).hash(state),
JsVariant::Float64(rational) => RationalHashable(rational).hash(state),which is exactly right — but a later "simplification" to integer.hash(state) would break it only for nonzero values, and nothing currently asserts that. A one-line comment there would also help.
Thanks for carrying this to a test — the -0.0 coverage is what makes the PR mergeable from my side.
|
Answering your three questions directly, so nothing is left hanging: 1. Review — done. I ran the mutation check described above on 2. Approve and merge — not something I can do, and that is the only thing blocking. The PR already reports 3. Pending workflows — nothing for you to do. Approving a workflow run for a first-time contributor is a maintainer click on the run page; it cannot be done from the PR branch. Waiting is the correct action. The two notes I left above (the Thanks for turning the report into a patch with tests; that is more than most reports get. |
|
Thank you, @newmathphys, for taking the time to independently verify the fix and provide such a detailed review. I really appreciate the effort you put into testing the implementation and explaining the backend-specific behaviour. Your insights regarding NaN normalization across the nan_boxed and jsvalue-enum backends were particularly helpful. I also appreciate the suggestion to add a nonzero cross-variant test (JsValue::new(1) and JsValue::new(1.0)) to further strengthen the regression coverage. I'll look into incorporating this additional test and making the relevant improvements. Thanks again for the thorough verification, valuable suggestions, and guidance! |
Test262 conformance changes
Tested main commit: |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #5702 +/- ##
===========================================
+ Coverage 47.24% 63.03% +15.78%
===========================================
Files 476 538 +62
Lines 46892 58586 +11694
===========================================
+ Hits 22154 36927 +14773
+ Misses 24738 21659 -3079 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This PR fixes the inconsistency between JsValue equality and hashing for signed zero values.
Previously, RationalHashable used Number::same_value() for equality while hashing the raw f64 bit representation. This caused +0.0 and -0.0 to compare equal but potentially produce different hashes.
Changes:
Testing:
Related issue:
Fixes #5678
@victrvondoom had previously expressed interest in working on this issue. The maintainer confirmed that there had been no subsequent PR or discussion update and invited me to proceed with the implementation.
Mentioning this for transparency.