Skip to content

fix: encode UNIXMS/UNIXMICRO times outside the UnixNano range - #826

Open
NgoQuocViet2001 wants to merge 1 commit into
rs:masterfrom
NgoQuocViet2001:fix-unix-time-overflow
Open

NgoQuocViet2001 wants to merge 1 commit into
rs:masterfrom
NgoQuocViet2001:fix-unix-time-overflow

Conversation

@NgoQuocViet2001

Copy link
Copy Markdown

With TimeFieldFormat set to TimeFormatUnixMs or TimeFormatUnixMicro, the JSON encoder computed the value as t.UnixNano()/div. UnixNano overflows for times before 1678 or after 2262, so the zero time.Time and far-future sentinels are logged as unrelated dates, while TimeFormatUnix prints the same values correctly:

UNIXMS before: {"zero":-6795364578871,"never":-4852116232933}
UNIXMS after:  {"zero":-62135596800000,"never":253402300799000}

AppendTime now uses t.UnixMilli() and t.UnixMicro(), and AppendTimes scales seconds and nanoseconds separately in the same way. UNIXNANO output is unchanged. One visible side effect: pre-1970 times with a sub-unit fraction now round down like TimeFormatUnix and UnixMilli (time.Unix(-1, 999999000) gives -1 ms instead of 0). I can drop that test case if you prefer a narrower change. #813 fixes the parsing side in ConsoleWriter and is independent of this one.

  • Ran: go test ./..., go test -tags binary_log ./..., go vet ./... and gofmt -l on the changed files: all clean.
  • Checked: the new TestAppendTimeUnixOutsideNanoRange fails on master with 10 assertion failures and passes with the fix.
  • Checked: AppendTimes matches UnixMilli, UnixMicro and UnixNano for 200k random times between years 1 and 9999, and a 10-value UNIXMS benchmark shows no slowdown.

The JSON encoder derived UNIXMS and UNIXMICRO values from
t.UnixNano(), which overflows int64 for times before 1678 or after
2262. The zero time.Time and far-future sentinels such as 9999-12-31
were logged as unrelated dates, while TimeFormatUnix printed them
correctly.

Use t.UnixMilli and t.UnixMicro in AppendTime, and scale seconds and
nanoseconds separately in AppendTimes. Pre-1970 times with a sub-unit
fraction now round down like TimeFormatUnix and time.Time.UnixMilli
instead of toward zero. UNIXNANO output is unchanged.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant