Skip to content

fix: Parse infinity, BC dates, and years beyond 9999 in dates and timestamps - #660

Merged
krlmlr merged 2 commits into
mainfrom
claude/fix-datetime-parsing
Nov 29, 2026
Merged

krlmlr merged 2 commits into
mainfrom
claude/fix-datetime-parsing

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Closes #655.

PqColumnDataSource::fetch_date() and PqColumnDataSource::convert_datetime() read date, timestamp and timestamptz values at fixed character positions. infinity, -infinity, BC dates and years above 9999 came back as garbage, and a value shorter than the fixed layout (infinity) was read past its end. Both parsers now walk the value with small helpers that bounds-check every position against val + strlen(val); no new PQgetvalue()/PGresult reads were added.

Behavior now:

  • infinity and -infinity give Inf and -Inf for Date and for timestamptz (POSIXct).
  • A BC suffix (which PostgreSQL emits after any UTC offset) gives astronomical years: 1 BC is year 0, 44 BC is year -43.
  • Years with more than four digits are parsed (up to 5874897 for date, 294276 for timestamps); a year beyond PostgreSQL's maximum gives NA, since days_from_civil() would overflow int.
  • UTC offsets +HH, +HH:MM and +HH:MM:SS are honored. The seconds part is new: before, +05:53:28 (local mean time before 1854 in Asia/Kolkata) was read as +05:53, giving a result 28 seconds off.
  • Fractional seconds are parsed digit by digit instead of with strtod(), so they no longer depend on the locale.
  • A value in any other shape (e.g. a DateStyle changed by the user) gives NA instead of garbage.

time/timetz (fetch_time()) were checked and left alone: PostgreSQL always emits at least HH:MM:SS, so its fixed positions stay inside the value, and an ASan run over time and timetz values on main reported nothing.

timestamp without time zone: the C++ side now returns Inf/-Inf, but fix_timezone() in R/PqResult.R calls lubridate::force_tz(), which turns them into NA. The result is now stable across queries, but not infinite; see the accepted limitations.

Sanitizer evidence

ASan build (-fsanitize=address, libasan preloaded into R). The probe runs SELECT repeat('x', 1000) AS a, repeat('x', n) AS b, <value> AS c for n in 0 to 1100, so that the value lands at the end of a 2048-byte libpq result block at some n.

On main (41cd4be), with 'infinity'::timestamp:

ERROR: AddressSanitizer: heap-buffer-overflow
READ of size 1
    #0 in PqColumnDataSource::convert_datetime(char const*) src/PqColumnDataSource.cpp:146
    #1 in PqColumnDataSource::fetch_datetime_local() const src/PqColumnDataSource.cpp:92
    #2 in DbColumnStorage::fetch_value() src/DbColumnStorage.cpp:154
is located 0 bytes after 2048-byte region
allocated by thread T0 here:
    #0 in malloc
    #1 (libpq.so.5+0x178b9)
    #2 in PQsetResultAttrs (libpq.so.5)

With 'infinity'::date on main:

ERROR: AddressSanitizer: heap-buffer-overflow
    #0 in PqColumnDataSource::fetch_date() const src/PqColumnDataSource.cpp:87
is located 0 bytes after 2048-byte region

On this branch, the same probe over infinity/-infinity for date, timestamp and timestamptz, BC dates and timestamps, a year-10000 timestamp, time and timetz: no error. The full test suite under the ASan build also reports no error.

Tests

New tests/testthat/test-datetime-parsing.R covers infinite values, results independent of the rest of the query, BC dates and years above 9999 for date, timestamp and timestamptz (checked against PostgreSQL's own extract(epoch ...) and date differences), fractional seconds, and offsets with seconds. It fails on main and passes here; devtools::test() passes locally against PostgreSQL 16.

Review

A clean review found nothing above Low. Its equivalence check: 1e5 random timestamps in six time zones are bit-identical to main except for two improvements, BC and large years match extract(epoch ...), and ASan and UBSan runs are clean. The one Low finding that needed a fix (year overflow in days_from_civil()) is fixed; the remaining limitations are listed in the Accepted limitations comment.

ALTREP phase 1 (#632) will move these parsers into shared functions and carry this fix along.

Session: https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g


Generated by Claude Code

…imestamps

`fetch_date()` and `convert_datetime()` read dates and timestamps at fixed character positions.
`infinity`, `-infinity`, BC dates, and years above 9999 came back as garbage,
and a short value such as `infinity` was read past its end.
The parsers now walk the value with a bounds check at every position.
`infinity` and `-infinity` become `Inf` and `-Inf`,
a ` BC` suffix gives astronomical years (1 BC is year 0),
and offsets from UTC with seconds, as PostgreSQL emits for local mean time, are honored.
A value in any other shape gives `NA`.

Closes #655.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: should 'infinity'::timestamp (without time zone) come back as Inf rather than NA?

With this PR the C++ parser returns Inf/-Inf for all three types, and date and timestamptz reach R as Inf/-Inf. For timestamp without time zone, fix_timezone() then calls lubridate::force_tz() (R/PqResult.R line 92), which turns Inf and -Inf into NA, even for timezone = "UTC". The result no longer changes between queries (the test only asserts it is not finite and stable, test lines 17–31), but the sign is lost. This PR was scoped to the C++ parsing functions, so it leaves R/PqResult.R alone. If nobody decides, timestamp infinities stay NA.

  • Fix it in a follow-up PR: in fix_timezone(), apply force_tz() only to the finite values and keep Inf/-Inf, then tighten the test to Inf/-Inf (recommended)
  • Fix it in this PR
  • Keep NA for timestamp infinities

Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: what should a date or timestamp in an unexpected shape give?

RPostgres sets DateStyle to ISO, MDY on connect, so PostgreSQL always emits the ISO shape this PR parses. A user can still change it (e.g. SET datestyle TO 'German'), and then the values no longer match. On main such values came back as garbage; this PR returns NA for any value it cannot parse completely (fetch_date(), and the same in convert_datetime()). An error would be louder, but it would abort the whole fetch from C++ mid-result; a warning per value would flood the console. If nobody decides, NA stays.

  • Return NA silently (recommended)
  • Raise an error that names the value and suggests the ISO DateStyle
  • Return NA and warn once per fetch

Generated by Claude Code

`days_from_civil()` computes in `int` and overflows from year 5874898 on.
PostgreSQL never emits such a year, the largest `date` is in 5874897,
so a value beyond it now gives `NA` like any other unparseable value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: warn once per column when dates or timestamps cannot be parsed?

If a user changes DateStyle after connecting, unparseable values give NA silently. RPostgres sets iso, mdy at connect (R/dbConnect_PqDriver.R line 119), so this needs a deliberate change by the user. A warning once per column would point at the cause, but it needs per-column state in the fetch path. This narrows the earlier question on the same point. If nobody decides, the silent NA stays, as listed under "Accepted limitations".

  • Accept the silent NA (recommended)
  • Warn once per column with the offending value and a hint to use the ISO DateStyle

Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

  • src/PqColumnDataSource.cpp lines 157–161: under a non-ISO DateStyle set by the user after connecting, dates and timestamps come back as NA without a warning; main returned plausible-looking wrong dates instead. RPostgres sets datestyle 'iso, mdy' at connect. See the question. Relevance low, confidence high.
  • R/PqResult.R line 92: 'infinity'::timestamp (without time zone) becomes NA in R, because force_tz() in fix_timezone() drops Inf; main gave garbage. See the question. Relevance medium, confidence high.

Generated by Claude Code

@krlmlr
krlmlr marked this pull request as ready for review November 29, 2026 12:25
@krlmlr
krlmlr merged commit f426684 into main Nov 29, 2026
9 checks passed
@krlmlr
krlmlr deleted the claude/fix-datetime-parsing branch November 29, 2026 19:22
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.

Dates and timestamps outside years 0001 to 9999, and infinity, are read as garbage, with a probable out-of-bounds read

2 participants