Skip to content

helpers/templates: fix FloatToTime int64 overflow at 2^63 nanoseconds - #1055

Open
xgbtxy wants to merge 1 commit into
prometheus:mainfrom
xgbtxy:fix/templates-float-to-time-overflow
Open

xgbtxy wants to merge 1 commit into
prometheus:mainfrom
xgbtxy:fix/templates-float-to-time-overflow

Conversation

@xgbtxy

@xgbtxy xgbtxy commented Nov 25, 2026

Copy link
Copy Markdown

Summary

Fix an int64 boundary overflow in helpers/templates.FloatToTime:

timestamp := v * 1e9
if timestamp > math.MaxInt64 || timestamp < math.MinInt64 {

In IEEE-754 float64, math.MaxInt64 (2^63 - 1 = 9223372036854775807) rounds up to 2^63 (9223372036854775808.0). When v = math.Exp2(63) / 1e9 (9223372036.8547764), v * 1e9 equals 9223372036854775808.0, so timestamp > math.MaxInt64 evaluates to false. The subsequent int64(timestamp) overflows to math.MinInt64, causing FloatToTime and HumanizeTimestamp to silently wrap year 2262 back to 1677-09-21 00:12:43.146 +0000 UTC instead of returning the overflow error.

Checking timestamp >= math.Exp2(63) (matching expfmt/openmetrics_parse.go) rejects 2^63 nanoseconds while keeping the full representable int64 range intact (math.Nextafter(math.Exp2(63)/1e9, 0) through -math.Exp2(63)/1e9).

Verification

  • Extended TestHumanizeTimestampError and added TestFloatToTimeInt64Boundary in helpers/templates/time_test.go.
  • Before the fix, both tests failed (An error is expected but got nil for math.Exp2(63)/1e9).
  • After the fix, go test -race -count=1 -v ./helpers/templates/..., go vet ./helpers/templates/..., and gofmt -l ./helpers/templates all pass.

Note: AI-assisted diagnosis and drafting; all code, tests, and local verification were reviewed and executed locally.

In IEEE-754 float64, math.MaxInt64 (2^63 - 1) rounds up to 2^63
(9223372036854775808.0). Consequently, FloatToTime(math.Exp2(63) / 1e9)
passed `timestamp > math.MaxInt64` and overflowed int64(timestamp) to
math.MinInt64, silently wrapping year 2262 to 1677-09-21 instead of
returning an overflow error.

Use `timestamp >= math.Exp2(63)` so 2^63 nanoseconds is rejected as
overflow while preserving the full representable int64 range.

Signed-off-by: Yan Chen <yan8925298@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 02:38

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 was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

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.

3 participants