Skip to content

fix Duration scaling by double saturating with the wrong sign - #2184

Open
dxbjavid wants to merge 1 commit into
abseil:masterfrom
dxbjavid:duration-scale-double-sign
Open

dxbjavid wants to merge 1 commit into
abseil:masterfrom
dxbjavid:duration-scale-double-sign

Conversation

@dxbjavid

@dxbjavid dxbjavid commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Scaling a Duration by a double goes through ScaleDouble, which multiplies or divides the seconds and subsecond parts of the representation separately and then adds the two partial results back together. The subsecond part is never negative, so for a negative duration that is not a whole number of seconds the two partials have opposite signs. Once the factor is large enough (around 1e299 for half a second) or the divisor small enough (around 1e-299), the subsecond partial overflows to infinity, and the sum is then either an infinity of the wrong sign or, when both partials overflow, a NaN that gets converted to int64_t. In practice absl::Milliseconds(-500) * 1e300 comes back as +InfiniteDuration rather than -InfiniteDuration, and absl::Milliseconds(-500) / denorm_min trips UBSan at the cast in SafeAddRepHi and returns ZeroDuration on arm64, so a negative remaining time scaled this way can turn into an unbounded wait. It came up while reading ScaleDouble: the existing tests for extreme factors only use whole-second durations, so the mixed-sign case is never exercised. I think the least intrusive fix is to saturate with the sign of the exact result as soon as either partial is not finite, which can only happen when the true value is far outside the Duration range, so in-range results should be unchanged. The new cases in InfinityMultiplication and InfinityDivision fail without the change and pass with it.

ScaleDouble scales rep_hi and rep_lo separately. rep_lo is never negative, so for a negative Duration with a subsecond part the two partial results have opposite signs, and once the rep_lo part overflows a double the sum is either an infinity of the wrong sign or a NaN that is then converted to int64_t. Saturate with the sign of the exact result as soon as either partial result is not finite.
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.

1 participant