Skip to content

Fix exponent/significand cohort comparison for differing byte lengths - #131205

Merged
tannergooding merged 1 commit into
dotnet:mainfrom
tannergooding:tannergooding-fix-total-order-exponent-compare
Jul 23, 2026
Merged

tannergooding merged 1 commit into
dotnet:mainfrom
tannergooding:tannergooding-fix-total-order-exponent-compare

Conversation

@tannergooding

Copy link
Copy Markdown
Member

Follow-up to #131087 (discussion here). @PranavSenthilnathan noted a correctness gap in TotalOrderIeee754Comparer<T>.CompareExponent.

Problem

CompareExponent's MSB-flip + SequenceCompareTo trick only produces the correct signed two's-complement order when both operands' exponent spans are the same length. For a custom IFloatingPointIeee754<T> whose GetExponentByteCount() returns a minimal, value-dependent two's complement byte count, the two exponents can have different byte lengths, and the naive comparison is wrong in that case (a 1-byte encoding of +5 can compare greater than a 2-byte encoding of +260).

The same latent issue existed in CompareSignificand's equal-bit-length fallback: byte count isn't guaranteed to match bit length, so two equal-bit-length significands can still be encoded with differing byte counts.

This only affects custom IFloatingPointIeee754<T> implementations reaching the generic path -- every built-in type (float, double, Half, BFloat16, NFloat, Decimal32/64/128) is fast-pathed earlier in Compare and is unaffected.

Fix

Add a shared CompareMagnitudeBigEndian(x, y, fill) helper that correctly compares differing-length big-endian magnitudes by treating the shorter span as sign/zero-extended with fill (0x00 for unsigned/non-negative, 0xFF for negative). Both CompareExponent and CompareSignificand's equal-bit-length branch now use it.


Also added two bit-length-driven fast paths to CompareExponent, since GetExponentShortestBitLength() is cheap to query:

  • For a fixed sign, the shortest two's complement bit length is monotonic in magnitude, so a bit-length mismatch settles same-sign comparisons without walking the full magnitude (mirrors the existing CompareSignificand pattern).
  • A bit length of 0 uniquely identifies an exponent value of exactly 0 (there's no negative-zero two's complement encoding), so a zero operand settles the comparison immediately, or lets a zero-vs-nonzero pair decide from just the nonzero operand's sign -- without ever reading the zero operand's raw bytes.

CompareMagnitudeBigEndian's leading-byte scan uses IndexOfAnyExcept instead of a manual loop.

Tests

  • Extended the existing byte-array-driven stub coverage with a new StubFloatingPointIeee754Cohort exercising same-length, differing-length, cross-sign, negation, and the new zero-bit-length fast path for the exponent cohort branch, plus a differing-byte-count case for the significand branch.
  • Added SingleWrapper/DoubleWrapper test types that wrap a real float/double to drive TotalOrderIeee754Comparer<T> through the fully generic path (which built-in types never reach, since Compare fast-paths them) and assert the result matches the real binary32/64 totalOrder semantics.
  • Verified red/green: reverting the fix reproduces the exact wrong-sign symptom described above (8 failures); restoring it passes all 188 tests.

Note

This PR description and the commit were drafted with GitHub Copilot assistance.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-numerics
See info in area-owners.md if you want to be subscribed.

Copilot AI 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.

Pull request overview

This PR fixes correctness in TotalOrderIeee754Comparer<T>’s fully-generic comparison logic when comparing exponents/significands whose big-endian encodings can legally differ in byte length (notably for custom IFloatingPointIeee754<T> implementations). It updates the generic exponent/significand comparison to be length-robust and extends test coverage to exercise these cases, including driving real float/double values through the generic path via wrapper types.

Changes:

  • Add a shared CompareMagnitudeBigEndian(ReadOnlySpan<byte> x, ReadOnlySpan<byte> y, byte fill) helper to correctly compare differing-length big-endian encodings via appropriate sign/zero extension.
  • Update CompareExponent to handle differing exponent byte lengths and add shortest-bit-length fast paths (including a zero-bit-length early decision).
  • Update CompareSignificand’s equal-bit-length branch to use the new helper, and expand tests to cover the new behaviors (including wrapper-driven generic-path validation for binary32/64).
Show a summary per file
File Description
src/libraries/System.Private.CoreLib/src/System/Numerics/TotalOrderIeee754Comparer.cs Makes generic exponent/significand comparisons correct when operand byte lengths differ by introducing CompareMagnitudeBigEndian and integrating bit-length fast paths in CompareExponent.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Numerics/TotalOrderIeee754ComparerTests.cs Adds targeted regression coverage for differing byte-length scenarios (exponent cohort + significand equal-bit-length cases) and validates generic-path behavior against real float/double via wrapper types.

Copilot's findings

  • Files reviewed: 2/2 changed files
  • Comments generated: 0

CompareExponent's MSB-flip + SequenceCompareTo trick only produces the
correct signed two's-complement order when both spans are the same
length; the same latent issue existed in CompareSignificand's
equal-bit-length fallback since byte count isn't guaranteed to match
bit length. Add a shared CompareMagnitudeBigEndian helper that
determines sign from the top bit (for the signed exponent case) and
compares differing-length big-endian magnitudes correctly by treating
the shorter span as sign/zero-extended.

Also add two bit-length-driven fast paths to CompareExponent:
- For a fixed sign, the shortest two's complement bit length is
  monotonic in magnitude, so a mismatch settles same-sign comparisons
  without walking the full magnitude (mirrors CompareSignificand).
- A bit length of 0 uniquely identifies an exponent value of exactly
  0 (there is no negative-zero encoding), so a zero operand settles
  the comparison, or lets the non-zero operand's sign alone decide,
  without reading either operand's raw exponent bytes.

Add SingleWrapper/DoubleWrapper test types that wrap a real float and
double to drive the fully generic CompareGeneric path (which the
built-in types themselves never reach, since Compare fast-paths them)
and assert its result matches the real binary32/64 totalOrder
semantics, in addition to the existing synthetic byte-array stubs.

Co-authored-by: Copilot App <[email protected]>
Copilot AI review requested due to automatic review settings July 22, 2026 17:35
@tannergooding
tannergooding force-pushed the tannergooding-fix-total-order-exponent-compare branch from bde795f to aad1bb1 Compare July 22, 2026 17:35

Copilot AI 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.

Copilot's findings

  • Files reviewed: 2/2 changed files
  • Comments generated: 0 new

@tannergooding
tannergooding enabled auto-merge (squash) July 22, 2026 17:47
@tannergooding
tannergooding merged commit ca428fe into dotnet:main Jul 23, 2026
138 of 141 checks passed
@tannergooding
tannergooding deleted the tannergooding-fix-total-order-exponent-compare branch July 23, 2026 11:38
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-rc1 milestone Jul 24, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Aug 23, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants