Skip to content

fix: ensure JsValue equality and hashing consistency - #5702

Open
raghavagarwal-debug wants to merge 5 commits into
boa-dev:mainfrom
raghavagarwal-debug:fix/jsvalue-zero-hash
Open

raghavagarwal-debug wants to merge 5 commits into
boa-dev:mainfrom
raghavagarwal-debug:fix/jsvalue-zero-hash

Conversation

@raghavagarwal-debug

@raghavagarwal-debug raghavagarwal-debug commented Nov 30, 2026 •

Copy link
Copy Markdown

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:

  • Use Number::same_value_zero() for RationalHashable equality.
  • Normalize signed zero values before hashing.
  • Add regression tests for positive zero, negative zero, and integer zero.
  • Add HashSet and HashMap tests to verify collection behaviour.

Testing:

  • cargo test -p boa_engine — passed.
  • cargo fmt --all -- --check — passed.

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.

@raghavagarwal-debug
raghavagarwal-debug requested a review from a team as a code owner November 30, 2026 19:23
@github-actions github-actions Bot added C-Tests Issues and PRs related to the tests. Waiting On Review Waiting on reviews from the maintainers labels Nov 30, 2026
@github-actions github-actions Bot added this to the v0.23 milestone Nov 30, 2026

@abdulhamid999 abdulhamid999 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.

Audited core/engine/src/value/hash.rs, core/engine/src/value/equality.rs, and core/engine/src/builtins/number/mod.rs:

  • Switching RationalHashable::eq to Number::same_value_zero and normalizing self.0 == 0.0 to 0.0_f64.to_bits() cleanly fixes the Hash/Eq mismatch between -0.0, 0.0, and JsVariant::Integer32(0).
  • One remaining edge case — non-canonical NaN bit patterns: Number::same_value_zero(x, y) (builtins/number/mod.rs:906-912) returns true for any two NaN values regardless of sign or payload bits (e.g. f64::NAN vs -f64::NAN or f64::from_bits(0x7ff8_0000_0000_0001)). Right now RationalHashable::hash only normalizes 0.0, so self.0.to_bits() still produces distinct hashes for distinct NaN bit patterns that compare equal under RationalHashable::eq / JsValue::eq. Normalizing else if self.0.is_nan() { f64::NAN.to_bits() } keeps the Eq/Hash invariant intact for all f64 values as well.

@raghavagarwal-debug

raghavagarwal-debug commented Dec 1, 2026 •

Copy link
Copy Markdown
Author

@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 newmathphys 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.

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:

  1. The is_nan() branch is currently redundant: tag_f64 in value/inner/nan_boxed.rs already reduces any NaN to f64::NAN.to_bits() when the value is constructed, so a NaN with a foreign payload cannot reach Hash. I would keep the branch (defence in depth) but add one line saying why — otherwise a reader concludes that payloads can reach Hash, which contradicts the invariant the rest of the type relies on.
  2. The regression tests cover HashSet::contains(-0.0) and HashMap::get(-0.0) for floats, and hash equality for Integer32(0). A HashMap lookup 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.

@newmathphys

Copy link
Copy Markdown

Short follow-up: the NaN normalisation you mention is already in the version I reviewed (if self.0.is_nan() { f64::NAN.to_bits() }), so nothing further is needed on that side — my only suggestion there was a one-line comment explaining why the branch exists while tag_f64 already canonicalises at construction, so a later reader does not conclude that foreign NaN payloads can reach Hash.

@raghavagarwal-debug

Copy link
Copy Markdown
Author

@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 newmathphys 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.

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 with JsValue::new(0.0) closes the cross-variant case end-to-end, which was the test I could not do without a full boa_engine build 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.

@raghavagarwal-debug

Copy link
Copy Markdown
Author

@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.

@newmathphys

Copy link
Copy Markdown

One practical note while you wait, so "stuck CI" is not misread: right now GitHub reports the PR as review=REVIEW_REQUIRED (mergeable, 5 commits), and only labeler and manage_pr have run. The rest of the workflow set is waiting for a maintainer to approve the run for a first-time contributor — that is a policy gate on our side of the fence, not a problem with the patch.

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.

@raghavagarwal-debug

Copy link
Copy Markdown
Author

@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!

@raghavagarwal-debug

raghavagarwal-debug commented Dec 2, 2026 •

Copy link
Copy Markdown
Author

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!

@newmathphys

Copy link
Copy Markdown

Independent verification of 7f05a3a — the fix is correct, and the new tests are real regression tests. Two review notes below, both measured, not guessed; not an approval (maintainer call).

Mutation check (built locally at 7f05a3a, rustc 1.100.0)

I reverted pieces of the fix and re-ran cargo test -p boa_engine --lib value::tests::hash_rational:

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 fix

cannot 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.

@newmathphys

Copy link
Copy Markdown

Answering your three questions directly, so nothing is left hanging:

1. Review — done. I ran the mutation check described above on 7f05a3a (built locally, rustc 1.100.0): reverting the fix makes tests.rs:126 fail (hash(+0.0)=13646096770106105413 vs hash(-0.0)=17224059632725561478), so the -0.0 regression coverage is real. The fix itself is correct.

2. Approve and merge — not something I can do, and that is the only thing blocking. The PR already reports mergeable: MERGEABLE; the blocker is REVIEW_REQUIRED. That is for @jedel1043 and @HalidOdat — not a rights issue on your side.

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 NaN assertion only bites with --features jsvalue-enum, and the missing nonzero cross-variant pair new(1) vs new(1.0)) are optional cleanups, not blockers — I would not hold the merge for them.

Thanks for turning the report into a patch with tests; that is more than most reports get.

@raghavagarwal-debug

Copy link
Copy Markdown
Author

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!

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

Test262 conformance changes

Test result main count PR count difference
Total 53,578 53,578 0
Passed 51,457 51,457 0
Ignored 1,629 1,629 0
Failed 492 492 0
Panics 0 0 0
Conformance 96.04% 96.04% 0.00%

Tested main commit: 2d8a534c683d386144d202e88e642c7e09382e01
Tested PR commit: 7f05a3a83b46ea9c8849342bc4330dc6e790a4bf
Compare commits: 2d8a534...7f05a3a

@codecov

codecov Bot commented Dec 2, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.71429% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 63.03%. Comparing base (6ddc2b4) to head (7f05a3a).
⚠️ Report is 1090 commits behind head on main.

Files with missing lines Patch % Lines
core/engine/src/value/hash.rs 85.71% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

C-Tests Issues and PRs related to the tests. Waiting On Review Waiting on reviews from the maintainers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hash for JsValue is inconsistent with Eq for -0.0

3 participants